최종 연산
- forEach()
Stream<String> stream = Stream.of("하나","둘","셋","넷");
stream.forEach(System.out::println);
- 조건 검사 findFirst(), findAny()
IntStream intStream1 = IntStream.of(9,7,8,6,5,3,4);
IntStream intStream2 = IntStream.of(9,7,8,6,5,3,4);
OptionalInt result1 = intStream1.sorted().findFirst(); // 정렬 후 첫 번째 요소 반환
System.out.println(result1.getAsInt()); // 3
OptionalInt result2 = intStream2.sorted().findAny(); // 병렬 스트림에서 사용
System.out.println(result2.getAsInt()); // 3
* allMatch(), anyMatch(), noneMatch()
IntStream intStream3 = IntStream.of(9,7,8,6,5,3,4);
IntStream intStream4 = IntStream.of(9,7,8,6,5,3,4);
IntStream intStream5 = IntStream.of(9,7,8,6,5,3,4);
System.out.println(intStream3.anyMatch(n -> n > 8)); // 하나라도 존재 ? true
System.out.println(intStream4.allMatch(n -> n > 8)); // 모두가 조건에 맞나 ? false
System.out.println(intStream5.noneMatch(n -> n > 8)); // 조건에 맞는 게 없나 ? false
- 통계 count(), sum(), average(), max(), min()
IntStream intStream6 = IntStream.of(1,2,3,4,5,6);
System.out.println(intStream6.count()); // 6
IntStream intStream7 = IntStream.of(1,2,3,4,5,6);
System.out.println(intStream7.sum()); // 21
DoubleStream intStream8 = DoubleStream.of(1,2,3,4,5,6);
System.out.println(intStream8.average().getAsDouble()); // 3.5
IntStream intStream9 = IntStream.of(1,2,3,4,5,6);
System.out.println(intStream9.max().getAsInt()); // 6
IntStream intStream10 = IntStream.of(1,2,3,4,5,6);
System.out.println(intStream10.min().getAsInt()); // 1
- 리듀싱 reduce() 스트림의 요소를 줄여가면서 누적연산을 수행.
IntStream intStream11 = IntStream.of(1,2,3,7,8,9);
OptionalInt reduceMax = intStream11.reduce((a, b) -> a > b ? a : b);
System.out.println(reduceMax.getAsInt()); // 9
IntStream intStream12 = IntStream.of(1,2,3,7,8,9);
OptionalInt reduceMin = intStream12.reduce((a, b) -> a > b ? b : a);
System.out.println(reduceMin.getAsInt()); // 1
- collect()
스트림의 요소를 수집하는 최종 연산으로 리듀싱과 유사하다.
스트림 → 컬렉션 or 배열 ( toList(), toSet(), toMap(), toCollection(), toArray())
모든 요소를 컬렉션에 수집하려면 Collectors클래스의 toList()와 같은 메서드를 사용하면 된다. List나 Set이 아닌 특정 컬렉션을 지정하려면, toCollection()에 해당 컬렉션의 생성자 참조를 매개변수로 넣어준다.
//List
List<String> names = StuStream.map(Student::getName)
.collect(Collectors.toList());
//ArrayList
ArrayList<String> list = names.stream()
.collect(Collectors.toCollection(ArrayList::new));
//Map
Map<String,Student> map = StuStream
.collect(Collectors.toMap(p -> p.getName(),p->p));
//Array
Student[] stuNames = studentStream.toArray(Student::new);
Object[] stuNames = studentStream.toArray(); // 매개변수 생략시 Object[] 타입으로 생성
그룹화와 분할 - groupingBy(), partitioningBy()
그룹화는 스트림의 요소를 특정 기준으로 그룹화하는 것을 말하고,
분할은 스트림의 요소를 두 가지, 지정된 조건에 일치하는 그룹과 일치하지 않는 그룹으로의 분할을 의미한다.
그룹화와 분할의 결과는 Map에 담겨 반환된다. groupingBy()은 요소를 Function으로 partitioningBy()는 Predicate로 분류한다.
- partitioningBy()
Stream<Student> StuStream = Stream.of(
new Student(80,"aaa",false),
new Student(10,"bbb",true),
new Student(10,"ccc",true)
);
Map<Boolean,List<Student>> stuBygendar = StuStream
.collect(partitioningBy(Student::getMale));
List<Student> female = stuBygendar.get(false);
List<Student> male = stuBygendar.get(true);
- groupingBy()
Map<Student.LEVEL,Long> stuByLevel = StuStream
.collect(groupingBy(s -> {
if(s.getScore() >= 80) return Student.LEVEL.HIGH;
else if(s.getScore() >= 50) return Student.LEVEL.MID;
else return Student.LEVEL.LOW;
},counting())
);
for(Student.LEVEL key: stuByLevel.keySet()){
System.out.printf("[%s] - %d명", key, stuByLevel.get(key));
}
'Language > Java' 카테고리의 다른 글
[Java] static 키워드에 대해 알아보자 ! (0) | 2022.06.17 |
---|---|
[Java] 오버로딩 VS 오버라이딩 (0) | 2022.06.14 |
[Java]스트림(stream)(2/3) (0) | 2022.06.07 |
[Java]스트림(stream)(1/3) (0) | 2022.06.07 |
[Java] 람다식 (0) | 2022.06.06 |