一、將對象的list根據屬性分組
對象Apple:
@Data
public class Apple {
private int weight;
private String color;
}
//List 初始化
List<Apple> inventory=new ArrayList<Apple>();
Apple apple1=new Apple();
apple1.setColor("green");
apple1.setWeight(160);
Apple apple2=new Apple();
apple2.setColor("red");
apple2.setWeight(160);
Apple apple3=new Apple();
apple3.setColor("red");
apple3.setWeight(170);
inventory.add(apple2);
inventory.add(apple1);
inventory.add(apple3);
---------------未使用stream---------
//根據顏色分類
Map<String,List<Apple>> map=new HashMap<>();
for(Apple apple:inventory){
String color=apple.getColor();
List<Apple> apples = map.get(color);
if(apples==null){
apples =new ArrayList<>();
map.put(color,apples);
}
apples.add(apple);
}
System.out.println(map);
---------------使用stream---------
Map<String,List<Apple>> mapSteam=inventory.stream().collect(groupingBy(Apple::getColor));
一行代碼搞定
二、stream只能消費一次
List<String> list=new ArrayList<>();
list.add("java8");
list.add("in");
list.add("action");
Stream<String> stream = list.stream();
stream.forEach(System.out::println);
stream.forEach(System.out::println);//流只能消費一次,這一次輸出報錯:stream has already been operated upon or closed
三、steam根據對象屬性篩選list
List<Apple> newList=inventory.stream().filter(s ->s.getWeight()>150 ).collect(toList());
newList.stream().forEach(System.out::println);
List<String> list=new ArrayList<>();
list.add("java8");
list.add("in");
list.add(null);
List<Integer> lengthList=list.stream().filter(s -> s!=null).filter(s -> "java8".equals(s)).map(String::length).collect(Collectors.toList());
lengthList.stream().forEach(System.out::println);