티스토리 뷰

JAVA

[Stream] 결과값을 모으기

박중수 2015. 4. 2. 20:36

매우 간단하다.


List list = stream.collect(Collectors.toList());

Set set = stream.collect(Collectors.toSet());


collect 메소드를 사용하면 된다.


상세한 형태를 지정하려면


ArrayList list = stream.collect(Collectors.toCollection(ArrayList::new));


이렇게 하면 된다.



또한 String으로 된 결과를 모두 하나로 이으려면

String result = stream.collect(Collectors.joining());

//"a", "b", "c", "d" ==> "abcd"


구분자를 넣어 이으려면

String result = stream.collect(Collectors.joining(", "));

//"a", "b", "c", "d" ==> "a, b, c, d"




또한 Map에도 넣을 수가 있다.


Map<String, Person> map = stream.collect(Collectors.toMap(Person::getName, person->person));


또는


Map<String, Person> map = stream.collect(Collectors.toMap(Person::getName, Function.identity()));


둘 다 같은 작업이 수행된다.

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2025/04   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30
글 보관함