종우의 컴퓨터 공간
Stream in Java 본문
Introduced in Java 8, the Stream API is used to process collections of objects. A stream is a sequence of objects that various methods which can pipelined to produce the desired result.
The features of Java stream are
- A stream is not a data structure instead it takes input from the collections, Arrays, or I/O channels.
- Streams do not change the original data structure, they only provide the result as per the pipelined methods.
- Each intermediate operation is lazily executed and returns a stream as a result, hence various intermediate operations can be pipelined. Terminal operations mark the end of the stream and return the result.
Different Operations On Streams-
Intermediate Operations:
- map: The map method is used to returns a stream consisting of the results of applying the given function to the elements of this stream.
List number = Arrays.asList(2,3,4,5);
List square = number.stream().map(x->x*x).collect(Collectors.toList()); - filter: The filter method is used to select elements as per the Predicate passed as argument.
List names = Arrays.asList("Reflection","Collection","Stream");
List result = names.stream().filter(s->s.startsWith("S")).collect(Collectors.toList()); - sorted: The sorted method is used to sort the stream.
List names = Arrays.asList("Reflection","Collection","Stream");
List result = names.stream().sorted().collect(Collectors.toList());
Terminal Operations:
- collect: The collect method is used to return the result of the intermediate operations performed on the stream.
List number = Arrays.asList(2,3,4,5,3);
Set square = number.stream().map(x->x*x).collect(Collectors.toSet()); - forEach: The forEach method is used to iterate through every element of the stream.
List number = Arrays.asList(2,3,4,5);
number.stream().map(x->x*x).forEach(y->System.out.println(y)); - reduce: The reduce method is used to reduce the elements of a stream to a single value.
The reduce method takes a BinaryOperator as a parameter.List number = Arrays.asList(2,3,4,5);
int even = number.stream().filter(x->x%2==0).reduce(0,(ans,i)-> ans+i);
@Transactional(readOnly = true)
public List<PostsListResponseDto> findAllDesc() {
return postsRepository.findAllDesc().stream()
.map(PostsListResponseDto::new) == .map(posts -> new PostsListResponseDto(posts))
.collect(Collectors.toList()));
}
=> postsRepository.findAllDesc() 를 통해서 List<Posts>를 받아 온다음에 Stream API를 이용하여 .map을 통하여 필요한 정보만을 담은 PostListResponseDto를 만든 후에, .collect를 이용하여 List로 만들어서 반환한다.
'스프링 부트 (SpringBoot)' 카테고리의 다른 글
스프링 시큐리티(Spring Security)와 OAuth 2.0으로 로그인 기능 구현 (0) | 2021.07.15 |
---|---|
Optional in Java (0) | 2021.07.15 |
Querydsl 개념과 신텍스 (0) | 2021.07.14 |
머스테치(Mustache) 신텍스 (0) | 2021.07.13 |
제이쿼리(jQuery) js 신텍스 (0) | 2021.07.13 |