对于一个List
遍历:
List
过滤:
List> dataList = new ArrayList>();//添加数据Map map1 = new HashMap();map1.put("id", 1);map1.put("name", "张三");map1.put("age", 20);dataList.add(map1);Map map2 = new HashMap();map2.put("id", 2);map2.put("name", "李四");map2.put("age", 30);dataList.add(map2);//使用stream流进行过滤dataList.stream().filter(map -> (Integer) map.get("age") > 25).forEach(map -> { System.out.println("id:" + map.get("id") + ",name:" + map.get("name"));});
查询:
List> dataList = new ArrayList>();//添加数据Map map1 = new HashMap();map1.put("id", 1);map1.put("name", "张三");map1.put("age", 20);dataList.add(map1);Map map2 = new HashMap();map2.put("id", 2);map2.put("name", "李四");map2.put("age", 30);dataList.add(map2);//使用stream流进行查询Optional> optionalMap = dataList.stream().filter(map -> (Integer) map.get("id") == 1).findFirst();if (optionalMap.isPresent()) { Map map = optionalMap.get(); System.out.println("id:" + map.get("id") + ",name:" + map.get("name") + ",age:" + map.get("age"));}
去重:
List> dataList = new ArrayList>();//添加数据Map map1 = new HashMap();map1.put("id", 1);map1.put("name", "张三");map1.put("age", 20);dataList.add(map1);Map map2 = new HashMap();map2.put("id", 2);map2.put("name", "李四");map2.put("age", 30);dataList.add(map2);Map map3 = new HashMap();map3.put("id", 2);map3.put("name", "李四");map3.put("age", 30);dataList.add(map3);//使用stream流进行去重List> distinctList = dataList.stream().distinct().collect(Collectors.toList());distinctList.stream().forEach(map -> { System.out.println("id:" + map.get("id") + ",name:" + map.get("name") + ",age:" + map.get("age"));});
排序:
List> dataList = new ArrayList>();//添加数据Map map1 = new HashMap();map1.put("id", 1);map1.put("name", "张三");map1.put("age", 20);dataList.add(map1);Map map2 = new HashMap();map2.put("id", 2);map2.put("name", "李四");map2.put("age", 30);dataList.add(map2);Map map3 = new HashMap();map3.put("id", 3);map3.put("name", "王五");map3.put("age", 25);dataList.add(map3);//使用stream流进行排序List> sortedList = dataList.stream().sorted((map1, map2) -> (Integer) map1.get("age") - (Integer) map2.get("age")).collect(Collectors.toList());sortedList.stream().forEach(map -> { System.out.println("id:" + map.get("id") + ",name:" + map.get("name") + ",age:" + map.get("age"));});
分组:
List> dataList = new ArrayList>();//添加数据Map map1 = new HashMap();map1.put("id", 1);map1.put("name", "张三");map1.put("age", 20);dataList.add(map1);Map map2 = new HashMap();map2.put("id", 2);map2.put("name", "李四");map2.put("age", 30);dataList.add(map2);Map map3 = new HashMap();map3.put("id", 3);map3.put("name", "王五");map3.put("age", 25);dataList.add(map3);//使用stream流进行分组Map>> groupMap = dataList.stream().collect(Collectors.groupingBy(map -> (Integer) map.get("age")));for (Map.Entry>> entry : groupMap.entrySet()) { Integer age = entry.getKey(); List> list = entry.getValue(); System.out.println("年龄为" + age + "的人数为" + list.size());}
来源地址:https://blog.csdn.net/MidYear/article/details/131722819