Backend
home
📝

stream 예제 코드 14

생성일
2025/01/22 10:39
태그
Beverage.java
package com.stream4; import lombok.AllArgsConstructor; import lombok.Data; @Data @AllArgsConstructor public class Beverage { private String name; private int price; private boolean isIce; }
Java
복사
CollectExample
package com.stream4; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; public class CollectExample { public static void main(String[] args) { List<Beverage> bList = new ArrayList<>(); bList.add(new Beverage("아이스 아메리카노", 1500, true)); bList.add(new Beverage("아이스 아메리카노", 1500, true)); bList.add(new Beverage("따뜻한 바닐라 라떼", 3500, false)); bList.add(new Beverage("제로콜라", 2000, true)); bList.add(new Beverage("솔의눈", 2000, true)); bList.add(new Beverage("실론티", 1500, true)); // 2000원의 음료 List<Beverage> two$List = bList.stream().filter(b -> b.getPrice() == 2000).collect(Collectors.toList()); // bList.stream().filter(b -> b.getPrice() == 2000).toList(); System.out.println(two$List); System.out.println(); // 음료수 이름 길이가 3인 것들 Set<Beverage> threeSet = bList.stream().filter(b -> b.getName().length() == 3).collect(Collectors.toSet()); System.out.println(threeSet); // 음료 이름, 가격으로 구성된 것들 Map<String, Integer> iceMap = bList.stream() .distinct() .filter(b -> b.isIce()).collect(Collectors.toMap(b -> b.getName(), b -> b.getPrice())); System.out.println(); System.out.println(iceMap); } }
Java
복사
package com.stream4; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.stream.Collectors; // 카테고리 상품 코드에 참고 public class CollectExample2 { public static void main(String[] args) { List<Beverage> bList = new ArrayList<>(); bList.add(new Beverage("따뜻한 아메리카노", 1500, false)); bList.add(new Beverage("따뜻한 바닐라 라떼", 3500, false)); bList.add(new Beverage("핫초코", 3500, false)); bList.add(new Beverage("제로콜라", 2000, true)); bList.add(new Beverage("솔의눈", 2000, true)); bList.add(new Beverage("실론티", 2000, true)); Map<String, Boolean> newBList = bList.stream() .distinct() .collect(Collectors.toMap(b -> b.getName(), b -> b.isIce())); System.out.println(newBList); System.out.println("============"); // 여기서 활용한 로직을 잘 이해해야 함 Map<Boolean, List<Beverage>> isIceMap = bList.stream() .collect(Collectors.groupingBy(b -> (Boolean) b.isIce())); // 여기서 활용한 로직을 잘 이해해야 함 for (Map.Entry<Boolean, List<Beverage>> entry : isIceMap.entrySet()) { System.out.println(entry.getKey() + " : "); for (Beverage b : entry.getValue()) { System.out.println("\t" + b); } } List<Beverage> iceList = isIceMap.get(true); List<Beverage> hotList = isIceMap.get(false); System.out.println(iceList); System.out.println(hotList); System.out.println(); Map<Boolean, Double> isIceAvgPriceMap = bList.stream() .collect(Collectors.groupingBy( b -> b.isIce(), // Collectors.counting() Collectors.averagingDouble(b -> b.getPrice() ))); System.out.println(isIceAvgPriceMap); } }
Java
복사