java8 关于stream的一些简单使用

一、将对象的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);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值