java8 Stream - Collector(์ฝ๋ ํฐ)
- Stream์ ์ผ๋ฐ์ ์ธ List, Set๋ฑ์ผ๋ก ๋ณ๊ฒฝ์์ผ์ฃผ๋ Stream์ ์ต์ข ์ฒ๋ฆฌ ๋ฉ์๋
1. Stream.collect()
- ๋ฐ์ดํฐ์ ์ค๊ฐ์ฒ๋ฆฌํ, ๋ง์ง๋ง์ List,Set ๋ฑ์ ํํ๋ก ๋ณํํด์ฃผ๋ ์ญํ ์ ํ๋ค.
- ํ์ํ ์์๋ง ์ปฌ๋ ์ ์ผ๋ก ๋ด์ ์ ์๊ณ , ์์๋ค์ ๊ทธ๋ฃนํํ ํ, ์ง๊ณ(Reduction)ํ ์ ์๋ค.
2. Stream.collect() ์ ์ฌ์ฉ
- collect(Collector<T,A,R> collector)
- T : ํ๋ผ๋ฏธํฐ ๊ฐ, Stream์ ์์
- A : ๋์ ๊ธฐ, ๋์ ์ฐ์ฐ์ ์คํํ ํจ์
- R : ๋ฆฌํด๊ฐ, ๋์ ์ฐ์ฐ์ ๊ฒฐ๊ณผ๊ฐ ์ ์ฅ๋๋ ๊ฐ์ฒด
3. Collector์ ๋ฉ์๋
toList, toSet
- Stream์ ๋ชจ๋ elements๋ค์ List๋ Set ์ผ๋ก ๋ณ๊ฒฝ์์ผ์ฃผ๋ ๋ฉ์๋์ด๋ค.
List<String> clist = Arrays.asList("a", "b", "c", "abc", "abc");
List<String> result = clist.stream().collect(Collectors.toList());
System.out.println("result = " + result); //result = [a, b, c, abc, abc]
List<String> clist = Arrays.asList("a", "b", "c", "abc");
Set<String> result = clist.stream().collect(Collectors.toSet());
System.out.println("result = " + result); //result = [a, b, c, abc]
- ์์ฉ
List<String> clist = Arrays.asList("a", "b", "c", "abc", "abc");
List<String> result = clist.stream()
.filter(list -> list.startsWith("a"))
.collect(Collectors.toList());
System.out.println("result = " + result); //result = [a, abc, abc]
→ Stream์ filter()๋ฉ์๋๋ฅผ ์ฌ์ฉํด์ a๋ก ์์ํ๋ elements๋ค๋ง ์ ๋ณํ์ฌ Listํํ๋ก ์ถ๋ ฅ
toCollection(Supplier<Collection>)
- ์ผ๋ฐ์ ์ธ List,Setํํ๋ณด๋ค ๋ ํน์ ํ ์๋ฃํ์ผ๋ก ์์ฑํ๊ณ ์ถ์๋ ์ฌ์ฉํ๋ค
- ์๋๋ Listํํ๋ฅผ ArrayListํํ๋ก ์์ฑํ ๋ชจ์ต
List<String> clist = Arrays.asList("a", "b", "c", "abc", "abc");
ArrayList<String> collect = clist.stream().collect(Collectors.toCollection(ArrayList::new));
System.out.println("collect = " + collect); //collect = [a, b, c, abc, abc]
toMap
- Stream์ elements๋ค์ Map ํํ๋ก ์์ฑํด์ฃผ๋ ๋ฉ์๋
- keyMapper, ValueMapper๋ฅผ ์ด์ฉํด์ ์ฒ๋ฆฌ
List<String> clist = Arrays.asList("a", "b", "c", "abc", "abc");
Map<String, Integer> collect = clist.stream().collect(Collectors.toMap(p -> p, String::length, (old, newInteger) -> old));
System.out.println("collect = " + collect); //collect = {a=1, b=1, abc=3, c=1}
→ toMap์ ํตํด์ key๋ clist์ key๋ก ์ฌ์ฉํ๊ณ , value๋ key.length๋ก ์ฌ์ฉ
→ key๊ฐ์์ “abc”๊ฐ 2๊ฐ๋ก์ค๋ณต์ด ๋ฐ์ํ ๊ฒจ์ฐ, ๊ธฐ์กด์ ๊ฐ์ ์ฌ์ฉํ๊ฒ ๋ค๊ณ ๋ช
์
Joining
- Stream์ Stringํ์ผ๋ก ํฉ ํด์ค๋ค.
List<String> clist = Arrays.asList("a", "b", "c", "abc", "abc");
String collect = clist.stream().collect(Collectors.joining());
System.out.println("collect = " + collect); //collect = abcabcabc
grouping
- ์ํ๋ ์กฐ๊ฑด๋๋ก Stream์ elements๋ฅผ Groupingํด์ฃผ๋ ๊ธฐ๋ฅ์ด๋ค.
List<String> clist = Arrays.asList("a", "b", "c", "abc", "abc");
Map<Integer, List<String>> collect = clist.stream().collect(Collectors.groupingBy(String::length, Collectors.toList()));
System.out.println("collect = " + collect); //collect = {1=[a, b, c], 3=[abc, abc]}
→ String.length์ ๊ฐ์ ๋ฐ๋ผ์ grouping
counting
- Stream์ elements์ ์๋ฅผ ์ธ์ ๋ฆฌํดํด์ค๋ค.
List<String> clist = Arrays.asList("a", "b", "c", "abc", "abc");
Long collect = clist.stream().collect(Collectors.counting());
System.out.println("collect = " + collect); //collect = 5
๋ฐ์ํ