collect 메서드를 이용해 축약된 결과로 반환하는 Java8 Stream API 입니다.
Collector 인스턴스를 활용하여 collect 메서드를 사용합니다.
입력 받은 요소를 새로운 List로 반환합니다.
반환된 list는 스레드 안전하며 변경이 필요하면 추가적인 제어를 할 수 있습니다.
@Test
public void testCollectorsToList() {
List<String> names = students.stream()
.map(n -> n.getName())
.collect(Collectors.toList());
System.out.println("to list " + names);
}
---출력결과---
to list [Jun, Kane, Din, Dao, Key, Pan]
입력 받은 요소를 새로운 Set로 반환합니다.
반환된 Set은 스레드 안전하며 변경이 필요하다면 추가적인 제어를 할 수 있습니다.
@Test
public void testCollectorsSet() {
Set<String> names = students.stream()
.map(n -> n.getName())
.collect(Collectors.toSet());
System.out.println("set " + names);
}
---출력결과---
to set [Jun, Dao, Din, Pan, Kane, Key]
입력 받은 요소를 새로운 컬렉션 객체로 반환합니다.
LinkedList와 같이 컬렉션을 선택하여 사용할 수 있습니다.
@Test
public void testCollectorsToCollection() {
LinkedList<String> names = students.stream()
.map(n -> n.getName())
.collect(Collectors.toCollection(LinkedList::new));
System.out.println("toCollection " + names);
}
---출력결과---
toCollection [Jun, Kane, Din, Dao, Key, Pan]
스트림을 Map 인스턴스를 사용하여 생성합니다.
사용할 Key 값과 키에 대한 Value 값을 매개 변수로 설정합니다.
@Test
public void testCollectorsToMap() {
try {
Map<String, Integer> names = students.stream()
.map(n -> n.getName())
.collect(Collectors.toMap(s -> s, s -> s.length()));
System.out.println(names);
} catch (IllegalStateException e) {
throw new IllegalStateException("Duplicate key excetion");
}
}
---출력결과---
{Jun=3, Dao=3, Din=3, Pan=3, Key=3, Kane=4}
위의 코드 내용에서는 중복된 키 값이 존재하는 경우 예외가 발생합니다.
중복된 키 값이 존재하더라도 예외를 발생하지 않는 방법이 있습니다.
BinaryOperator를 매개 변수로 사용하는 오버로드된 toMap()을 사용하면 됩니다.
BinaryOperator는 중복된 키 값을 발견하면 첫 번째 키 값을 사용하도록 되어 있습니다.
Represents an operation upon two operands of the same type, producing a result of the same type as the operands. This is a specialization of BiFunction for the case where the operands and the result are all of the same type.
BinaryOperator는 두 개의 피연산자를 연산을 통해 피연산자와 동일한 유형으로 값을 반환하는 BiFunction 입니다.
BiFunction은 두 개의 인수로 결과를 만드는 함수를 의미합니다.
@Test
public void testCollectorsToMapPossibleDuplicate() {
Map<String, Integer> names = duplicateStudents.stream()
.map(n -> n.getName())
.collect(Collectors.toMap(s -> s, s -> s.length(), (s1, s2) -> s1));
System.out.println("binary operation " + names);
}
---출력결과---
binary operation {Jun=3, Dao=3, Din=3, Pan=3, Kane=4}
추가로 스트림을 HashMap으로 만드는 toMap()이 존재합니다.
@Test
public void testCollectorsToMapConvertToHashMap(){
Map<String, Integer> names = students.stream()
.map(n -> n.getName())
.collect(Collectors.toMap(s -> s , s -> s.length(), (s1, s2) -> s1, HashMap::new));
}
---출력결과---
hash map {Jun=3, Dao=3, Din=3, Pan=3, Key=3, Kane=4}
주어진 컬렉터로 값을 반환하고 반환된 값은 변경할 수 없습니다.
@Test
public void testCollectorsCollectingAndThen() {
List<String> list = new ArrayList<>();
list.add("A");
list.add("B");
list.add("C");
list.add("D");
List<String> unmodifiableList = list.stream()
.collect(Collectors.collectingAndThen(Collectors.toList(), Collections::unmodifiableList));
System.out.println(unmodifiableList);
}
---출력결과---
[A, B, C, D]
[JUnit5] 모듈 구조 - Platform, Jupiter, Vintage (0) | 2021.08.02 |
---|---|
[Stream] collect method (0) | 2020.08.04 |
[Stream] finding operation (0) | 2020.07.30 |
[Stream] reduce method (0) | 2020.07.29 |
[Stream] Match method (0) | 2020.07.28 |
댓글 영역