Java

[Effective Java] ์•„์ดํ…œ 46. ์ŠคํŠธ๋ฆผ์—์„œ๋Š” ๋ถ€์ž‘์šฉ ์—†๋Š” ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•˜๋ผ.

quedevel 2023. 3. 22. 15:33
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
๋ฐ˜์‘ํ˜•