stream排序、筛选、截取、统计、多字段去重等操作 |
您所在的位置:网站首页 › stream按照某字段排序 › stream排序、筛选、截取、统计、多字段去重等操作 |
简单举例介绍比较方便不复杂的Stream流方法,提升编程效率 public class StreamTest { public static void main(String[] args) { Listmlist = new ArrayList(); TestData data; //字段名为name,time,age data = new TestData("大毛", "2020-01-01",21); mlist.add(data); data = new TestData("二毛", "2020-02-08",12); mlist.add(data); data = new TestData("三毛", "",23); mlist.add(data); data = new TestData("四毛", "2020-03-03",17); mlist.add(data); List squaresList = mlist.stream() //下面是筛选 .filter(o -> !o.getTime().contains("08")) .filter(o -> !o.getTime().isEmpty()) //下面是排序 .sorted(Comparator.comparing(TestData::getTime).reversed()) .sorted((o1,o2) -> o1.getAge()-o2.getAge()) //下面这一行把list列表数据返回,不写就是一个布尔类型结果返回 .collect(Collectors.toList()) //下面是截取,只取结果种的前两条数据 .subList(0,2); } } //提取list集合中的对象某个字段然后生成对应的新集合 List modelItemIds = casePo.getAssessment().getAssessmentItems().stream().map(AssessmentItemPo::getModelItemId).collect(Collectors.toList()); 字段累加求和 int total = list.stream().mapToInt(CaseInfoVO::getPersonValue).sum();concat:将格式相同的两个stream合并在一起 skip:跳过 Stream.concat(manArray.stream().filter(s -> s.length() == 3).limit(3), womanList.stream().filter(s -> s.startsWith("林")).skip(1)).map(Actor::new). forEach(p -> System.out.println(p.getName()));筛选集合中某字段不为null或者“”的集合 List filterContentList = legalVos.stream().map(LegalVo::getContent).filter(StrUtil::isNotBlank).collect(Collectors.toList());对List(Map)进行 //方法一 dataList.stream().sorted(Comparator.comparing((Map h) -> ((String) h.get("dateTime")))).collect(Collectors.toList()); //方法二----添加静态方法 private static Integer sortMap(Map map){ return Integer.valueOf(map.get("evtId").toString()); } //比较方法中添加类名(SendServiceImpl)::静态方法(sortMap)即可 List newMapList = mapList.stream().sorted(Comparator.comparing(SendServiceImpl::sortMap)).collect(Collectors.toList());;多字段去重 //去重 ArrayList collect = maps.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet(Comparator.comparing(o -> o.get("currentDepartName") + ";" + o.get("currentUserName") + ";" + o.get("handleType") + ";" + o.get("nextDepartName")))), ArrayList::new)); |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |