package com.stream4;
import lombok.AllArgsConstructor;
import lombok.Data;
@Data
@AllArgsConstructor
public class Beverage {
private String name;
private int price;
private boolean isIce;
}
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);
}
}
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);
}
}