2021-03-19 09:40:05
本文主要介绍了java8使用流的filter来筛选数据的实现,分享给大家,具体如下:
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 { https://比如说 你需要在一个列表中 筛选出所以重量大于150的苹果,然后按照颜色分组 https://按常规的筛选写法 就是在循环里面 迭代筛选 public static void main(String[] args) { List<Apple> appleList = new ArrayList<>(); https://常规写法 Map<String, List<Apple>> AppMap = new HashMap<>(); for (Apple apple : appleList) { if (apple.getWeight() > 150) { https://如果重量大于150 if (AppMap.get(apple.getColor()) == null) { https://该颜色还没分类 List<Apple> list = new ArrayList<>(); https://新建该颜色的列表 list.add(apple);https://将苹果放进去列表 AppMap.put(apple.getColor(),list);https://将列表放到map中 }else { https://该颜色分类已存在 AppMap.get(apple.getColor()).add(apple);https://该颜色分类已存在,则直接放进去即可 } } } https://如上方式 就可以筛选出来所有的150克大小以上的苹果,并按颜色分类 https://方式二 使用java8提供的流api实现 这种叫内部迭代 Map<String, List<Apple>> AppMap2=appleList.stream().filter((Apple a)->a.getWeight()>150) https://筛选出大于150的 .collect(groupingBy(Apple::getColor)); https://按颜色分组 最后得到map } class Apple { private String color;https://颜色 private Integer weight; https://重量 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; } } }
原文链接:http://www.yuepc.com/a/11209.html
http://www.yuepc.com 为 “沈一博客” 唯一官方服务平台,请勿相信其他任何渠道。
2021-06-04
2021-06-10
2021-04-30
2021-06-12
2021-05-13
2021-05-09
2021-05-02
2021-06-10
2021-06-13
2021-06-13