Java8에서 추가된 Streams에 아주 기본적인 것을 알아봅니다.
Stream API
Stream은 데이터의 흐름입니다. 배열 또는 컬렉션 인스턴스에 함수 여러개를 조합해서 원하는 결과를 필터링하고 가공된 결과를 얻을 수 있습니다.
예를 들어: Collection<Widget>인 widgets을 stream의 소스로 사용하여 해당 stream에 대해 필터링을 하고 map-reduce를 수행하여 빨간색 위젯의 가중치 합계를 얻을 수 있습니다.
int sum = widgets.stream()
.filter(b -> b.getColor() == RED)
.mapToInt(b -> b.getWeight())
.sum();
Stream 생성하기
String[] arr = new String[]{"a", "b", "c"};
Stream<String> stream = Arrays.stream(arr);
stream = Stream.of("a", "b", "c");
배열로 된 stream을 생성하기 위해선 Arrays.stream 메서드를 사용합니다.
멀티스레딩에서의 Stream
Stream API는 parallelStream() 를 사용하여 간단하게 멀티스레딩 환경에서 병렬로 Stream의 요소를 실행할 수 있습니다.
int sumOfWeights = widgets.parallelStream()
.filter(b -> b.getColor() == RED)
.mapToInt(b -> b.getWeight())
.sum();
반복하기 (Iterating)
for문과 if 문을 사용하여 list에 "test"라는 값이 있으면 true를 리턴해봅시다.
for (String string : list) {
if (string.contains("test")) {
return true;
}
}
Java8에서는 stream을 이용해서 한 줄로 작성할 수가 있습니다.
boolean isExist = list.stream().anyMatch(element -> element.contains("test"));
Matching
어떤 값이 일부분 일치하는지, 전부 일치하는지, 하나도 일치하지 않는지 판단이 필요할때가 있죠? 그럴땐 anyMatch(), allMatch(), noneMatch()를 이용하면 됩니다.
List<String> days = Arrays.asList("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday");
boolean isAnyElementMatch = days.stream()
.anyMatch(x-> x instanceof String)
boolean isAllElementMatch = days.stream()
.allMatch(x-> x instanceof String)
boolean isNoneElementMatch = days.stream()
.noneMatch(x-> x instanceof String)
System.out.println("anyMatch = " + isAnyElementMatch); // true
System.out.println("allMatch = " + isAllElementMatch); // true
System.out.println("noneMatch = " + isNoneElementMatch); // false
Collecting
Stream의 collect() 메소드를 사용하여 element를 대문자로 변환후에 Collection 형태인 List<String>로 리턴이 가능합니다.
List<String> resultList
= list.stream().map(element -> element.toUpperCase()).collect(Collectors.toList());
Reduction operations
입력한 값들의 sum을 구하고 싶을 땐 reduce 함수를 사용할 수 있습니다.
int sum = numbers.stream().reduce(0, (x,y) -> x+y);
or :
int sum = numbers.stream().reduce(0, Integer::sum);
Mutable reduction
input으로 들어온 값을 변경을 해서 리턴하고 싶을때도 reduce 함수를 사용할 수 있습니다.
String concatenated = strings.reduce("", String::concat)
'개발&프로그래밍' 카테고리의 다른 글
[Spring] 스프링 웹 어노테이션 (Spring Web Annotation) (0) | 2022.03.15 |
---|---|
[Spring] @Controller 과 @RestController 어노테이션 (0) | 2022.03.14 |
[Spring] Spring Boot 프로젝트 시작하기 (0) | 2022.03.14 |
[JAVA] Java8 Stream Skip()과 limit() (0) | 2022.03.14 |
[JAVA] String 문자열 선언과 사용 (0) | 2022.03.13 |
댓글