JAva 8はストリームのfilterを使用してデータをフィルタします
1743 ワード
package chapter1;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static java.util.stream.Collectors.groupingBy;
public class stream {
// 150 ,
//
public static void main(String[] args) {
List appleList = new ArrayList<>();
//
Map> AppMap = new HashMap<>();
for (Apple apple : appleList) {
if (apple.getWeight() > 150) { // 150
if (AppMap.get(apple.getColor()) == null) { //
List list = new ArrayList<>(); //
list.add(apple);//
AppMap.put(apple.getColor(),list);// map
}else { //
AppMap.get(apple.getColor()).add(apple);// ,
}
}
}
// 150 ,
// java8 api
Map> AppMap2=appleList.stream().filter((Apple a)->a.getWeight()>150) // 150
.collect(groupingBy(Apple::getColor)); // map
}
class Apple {
private String color;//
private Integer weight; //
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public Integer getWeight() {
return weight;
}
public void setWeight(Integer weight) {
this.weight = weight;
}
}
}