728x90
๋ฐ์ํ
๐ฏ ์์ดํ 46. ์คํธ๋ฆผ์์๋ ๋ถ์์ฉ ์๋ ํจ์๋ฅผ ์ฌ์ฉํ๋ผ.
์คํธ๋ฆผ ํ์ดํ๋ผ์ธ ํ๋ก๊ทธ๋๋ฐ์ ํต์ฌ์ ๋ถ์์ฉ ์๋ ํจ์ ๊ฐ์ฒด์ ์๋ค. ์คํธ๋ฆผ๋ฟ ์๋๋ผ ์คํธ๋ฆผ ๊ด๋ จ ๊ฐ์ฒด์ ๊ฑด๋ค์ง๋
๋ชจ๋ ํจ์ ๊ฐ์ฒด๊ฐ ๋ถ์์ฉ์ด ์์ด์ผ ํ๋ค. ์ข
๋จ ์ฐ์ฐ ์ค forEach
๋ ์คํธ๋ฆผ์ด ์ํํ ๊ณ์ฐ ๊ฒฐ๊ณผ๋ฅผ ๋ณด๊ณ ํ ๋๋ง ์ด์ฉํด์ผ ํ๋ค.
๊ณ์ ์์ฒด์๋ ์ด์ฉํ์ง ๋ง์. ์คํธ๋ฆผ์ ์ฌ๋ฐ๋ก ์ฌ์ฉํ๋ ค๋ฉด ์์ง๊ธฐ๋ฅผ ์ ์์๋ฌ์ผ ํ๋ค. ๊ฐ์ฅ ์ค์ํ ์์ง๊ธฐ ํฉํฐ๋ฆฌ๋ toList
, toSet
, toMap
, groupingBy
, joining
์ด๋ค.
- Collectors
/**
* Collectors
*/
List<Integer> integerList = Stream.of(3, 5, -3, 3, 4, 5).collect(java.util.stream.Collectors.toList());
System.out.println("integerList = " + integerList);
Set<Integer> integerSet = Stream.of(3, 5, -3, 3, 4, 5).collect(java.util.stream.Collectors.toSet());
System.out.println("integerSet = " + integerSet);
List<Integer> integerList1 = Stream.of(3, 5, -3, 3, 4, 5).collect(java.util.stream.Collectors.mapping(x -> Math.abs(x), java.util.stream.Collectors.toList()));
System.out.println("integerList1 = " + integerList1);
Set<Integer> integerSet1 = Stream.of(3, 5, -3, 3, 4, 5).collect(java.util.stream.Collectors.mapping(x -> Math.abs(x), java.util.stream.Collectors.toSet()));
System.out.println("integerSet1 = " + integerSet1);
int sum = Stream.of(3, 5, -3, 3, 4, 5).collect(java.util.stream.Collectors.reducing(0, (x,y)->x+y));
System.out.println("sum = " + sum);
- groupingBy
/**
* Grouping By
*/
List<Integer> integerList = Arrays.asList(13, 2, 101, 203, 304, 402, 305, 349, 2312, 203, 70);
Map<Integer, List<Integer>> integerListMap = integerList.stream().collect(Collectors.groupingBy(n -> n % 10));
System.out.println("integerListMap = " + integerListMap);
Map<Integer, List<String>> integerListMap1 = integerList.stream()
.collect(Collectors.groupingBy(n -> n % 10, Collectors.mapping(n -> "unit digit is " + n, Collectors.toList())));
System.out.println("integerListMap1 = " + integerListMap1);
- PartitioningBy
/**
* Partitioning By
*/
List<Integer> integerList = Arrays.asList(13, 2, 101, 203, 304, 402, 305, 349, 2312, 203, 70);
Map<Boolean, List<Integer>> booleanListMap = integerList.stream()
.collect(Collectors.partitioningBy(n -> n % 2 == 0));
System.out.println("booleanListMap = " + booleanListMap);
์ฐธ๊ณ ์๋ฃ
Joshua Bloch, ใEffective Java 3/Eใ, ๊ฐ์๋งต์ ์ฎ๊น, ํ๋ก๊ทธ๋๋ฐ์ธ์ฌ์ดํธ(2018)
http://www.kyobobook.co.kr/product/detailViewKor.laf?ejkGb=KOR&mallGb=KOR&barcode=9788966262281&orderClick=LEa&Kc=
728x90
๋ฐ์ํ