본문 바로가기

java

Reduce Max값 구하기

1. Collectors reducing을 이용하는 방법


Food food = Food.menu.stream().collect(Collectors.reducing((d1, d2) -> 
d1.getCalories() > d2.getCalories() ? d1 : d2)).get();


2. Collector maxBy를 이용하는 방법, 내부적으로는 Collectors의 reduce를 호출 함.

Food food1 = Food.menu.stream().collect(Collectors.maxBy(Comparator.comparingInt(Food::getCalories))).get();


3. Stream reduce를 이용하는 방법

Food food2 = Food.menu.stream().reduce((d1, d2) -> d1.getCalories() > d2.getCalories() ? d1 : d2).get();

4. Stream reduce는 BinaryOperator를 인자로 받는데 default 메소드로 max와 min이 구현되어 있음   

Food.menu.stream().reduce(BinaryOperator.maxBy(Comparator.comparingInt(Food::getCalories))).get()



enum Type {MEAT, FISH, OTHER}

class Food {
private final String name;
private final boolean vegetarian;
private final int calories;
private final Type type;

public Food(String name, boolean vegetarian, int calories, Type type) {
this.name = name;
this.vegetarian = vegetarian;
this.calories = calories;
this.type = type;
}

public String getName() {
return name;
}

public boolean isVegetarian() {
return vegetarian;
}

public int getCalories() {
return calories;
}

public Type getType() {
return type;
}
@Override
public String toString() {
return name;
}

public static final List<Food> menu =
Arrays.asList( new Food("pork", false, 1800, Type.MEAT),
new Food("beef", false, 7100, Type.MEAT),
new Food("chicken", false, 1400, Type.MEAT),
new Food("french fries", true, 1530, Type.OTHER),
new Food("rice", true, 3510, Type.OTHER),
new Food("season fruit", true, 1120, Type.OTHER),
new Food("pizza", true, 5150, Type.OTHER),
new Food("prawns", false, 1400, Type.FISH),
new Food("salmon", false, 4150, Type.FISH));

}


'java' 카테고리의 다른 글

ClassLoader  (0) 2017.10.14
GabageCollector  (0) 2017.10.14
GarbageCollection  (0) 2017.10.13
String StringBuider SttringBuffer 차이  (0) 2017.10.13
예외  (0) 2017.10.12