java collect

조항주·2022년 7월 12일

study

목록 보기
20/20
post-thumbnail

collect()

스트림의 요소를 수집하는 최종 연산
collect()가 스트림의 요소를 수집하기 위한 수집 방법이 정의된 것이 collector.
collector는 Collector인터페이스를 구현한 것.

collect() 스트림의 최종 연산. 매개변수로 collector가 필요하다.
Collector 인터페이스. collector는 이 인터페이스를 구현해야한다.
Collectors 클래스. static 메서드로 미리 작성된 collector를 제공한다.
collect()의 매개변수 타입은 Collector인데. 매개변수가 Collector를 구현한 클래스의 객체이어야 한다는 뜻.
그리고 collect()는 이 객체에 구현된 방법대로 스트림의 요소를 수집한다.

스트림을 컬렉션과 배열로 변환-toList(), toSet(), toMap(), toCollection(), toArray()

스트림의 모든 요소를 컬렉션에 수집하려면, Collectors클래스의 toList()와 같은 메서드를 사용하면 된다.
List나 Set이 아닌 특정 컬렉션을 지정하려면, toCollection()에 해당 컬렉션의 생성자 참조를 매개변수로 넣어주면 된다.

List<String> names = stuStream.map(Student::getName)
                              .collect(Collectors.toList());
ArrayList<String> list = names.stream()
                             .collect(Collectors.toCollection(ArrayList::new));

Map은 객체의 어떤 필드를 키와 값으로 사용하지 지정해야 한다.
요소의 타입이 Person인 스트림에서 사람의 주민번호(regId)를 키로 하고, 값으로 Person 객체를 그대로 저장

Map<String, Person> map = personStream.collect(Collectors.toMap(p->p.getRegId(), p->p)

스트림에 저장된 요소들을 T[] 타입의 배열로 변환하려면 toArray() 사용
단, 해당 타입의 생성자 참조를 매개변수로 지정해줘야 한다. 지정하지 않으면 반환되는 배열의 타입은 Object[]

Student[] stuNames = studentStream.toArray(Student[]::new);   // OK
Student[] stuNames = studentStream.toArray();                 // 에러
Object[] stuNames = studentStream.toArray();                  // OK

통계

counting(), summingInt(), averagingInt(), maxBy(), minBy()

문자열 결합

joining()
스트림의 요소가 String이나 StringBuffer처럼 CharSequence의 자손인 경우에만 결합 가능하므로
스트림의 요소가 문자열이 아닌 경우에는 먼저 map()을 이용해서 스트림의 요소를 문자열로 변환해야 한다.

String studentNames = stuStream.map(Student::getName).collect(joining());
String studentNames = stuStream.map(Student::getName).collect(joining(","));
String studentNames = stuStream.map(Student::getName).collect(joining(",", "[", "]"));

만약 map()없이 스트림에 바로 joining()하면, 스트림의 요소에 toString()을 호출한 결과를 결합한다.

String studentInfo = stuStream.collect(joining(","));

0개의 댓글