java8的新特性stream api使用
1、使用stream api对list集合做总数累加计算:
List<Integer> profitList = new ArrayList<Integer>(); //使用java8的新特性stream api 做list元素累加,算总和 int total = profitList.stream().mapToInt(t -> t).sum();
2、使用Stream api对List<map> 类型的集合做某值的总和计算(并且值的类型为BigDecimal类型数值)
List<Integer> doughnutProfitList= new ArrayList<Integer>(); //要处理的list合集
BigDecimal totalValue = new BigDecimal("0"); if(doughnutProfitList != null && doughnutProfitList.size() > 0){ totalValue = doughnutProfitList.stream().map(x -> new BigDecimal(String.valueOf(x.get("score")))).reduce(BigDecimal.ZERO,BigDecimal::add); }
3、Stream api过滤LIst<Map<String, Object>> 集合数据,根据条件过滤获取相应的List<Map<String, Object>>集合数据:
List<Map<String, Object>> list = new ArrayList<Map<String,Object>>(); Map<String,Object> mapOne = new HashMap<>(); mapOne.put("id",1 ); mapOne.put("name","aaa" ); mapOne.put("age",24 ); mapOne.put("address","11111" ); list.add(mapOne); Map<String,Object> mapTwo = new HashMap<>(); mapTwo.put("id",2 ); mapTwo.put("name","aaa" ); mapTwo.put("age",18 ); mapTwo.put("address","22222" ); list.add(mapTwo); Map<String,Object> mapThree = new HashMap<>(); mapThree.put("id",3 ); mapThree.put("name","bbb" ); mapThree.put("age",24 ); mapThree.put("address","33333" ); list.add(mapThree); //过滤:拿到list<String> List<String> listStr = list.stream().map(item -> item.get("name").toString()).collect(Collectors.toList()); System.out.println(listStr); //使用stream api摘出List<Map<String, Object>>集合:过滤得到name为aaa的list集合 List<Map<String, Object>> newLevel2List = new ArrayList<Map<String,Object>>(); newLevel2List = list.stream().filter(p -> p.get("name").toString().equals("aaa")).collect(Collectors.toList()); System.out.println(newLevel2List);
4、list数据使用stream流找出重复的数据:
public static <E> List<E> getDuplicateElements(List<E> list) { return list.stream() // list 对应的 Stream .collect(Collectors.toMap(e -> e, e -> 1, (a, b) -> a + b)) // 获得元素出现频率的 Map,键为元素,值为元素出现的次数 .entrySet().stream() // 所有 entry 对应的 Stream .filter(entry -> entry.getValue() > 1) // 过滤出元素出现次数大于 1 的 entry .map(entry -> entry.getKey()) // 获得 entry 的键(重复元素)对应的 Stream .collect(Collectors.toList()); // 转化为 List }
public static void main(String[] args) throws Exception {
List<String> list = Arrays.asList("a", "b", "c", "d", "a", "a", "d", "d","c","b","e","f");
List<String> duplicateElements = getDuplicateElements(list);
System.out.println("list 中重复的元素:" + duplicateElements);
}
5、求两个List<String>的差集:如:list1 = ['a', 'b', 'c'],list2 = ['b'],返回list1与list2的差集为:['a', 'c']
/** * descript: 求两个list的差集 * @author: zhouruntao * @date: 2023-04-06 20:01 * **/ public static List<String> subList(List<String> list1, List<String> list2){ Map<String, String> tempMap = list2.parallelStream().collect(Collectors.toMap(Function.identity(), Function.identity(), (oldData, newData) -> newData)); return list1.parallelStream().filter(str->{return !tempMap.containsKey(str);}).collect(Collectors.toList()); }
6、使用stream流,提取List<对象>中的某个字段:如id
List<TUser> cList = new ArrayList<TUser>();
List<Long> ids = cList.stream().map(TUser::getId).collect(Collectors.toList());
7、List<String> 去重
List<String> distinctStrings = strings.stream().distinct().collect(Collectors.toList());
8、List<Student> 对象去重:根据Student对象中的studentCode字段属性去重
List<Student> newStudentList = studentList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Student:: getStudentCode))), ArrayList::new));
9、使用Stream流,提取List中的对象集合,其中name为"abc"的元素对象
(比如:要取List<Student>集合中,把student对象的name值为“abc”的提取出来)
List<Student> studentList = testVo.getStudentList().stream().filter(studentVo -> "abc".equals(studentVo.getName())).findFirst();
99、按照各种java类型排序
借鉴博物:https://blog.csdn.net/weixin_52796198/article/details/130861941
2024年5月24日更新=====================================================
1、stream流循环简单数组,用来替代for,如操作Long[]数组
Long[] categoryIds = {1L, 2L, 3L, 4L};
Arrays.stream(categoryIds).forEach(f->{
logger.info("==================" + f);
});
2、stream流循环简单数组,并取下标:使用IntStream.range这个方法
Long[] categoryIds = {1L, 2L, 3L, 4L};
IntStream.range(0, categoryIds.length).forEach(index -> {
long value = categoryIds[index];
System.out.println("Index: " + index + ", Value: " + value);
});
3、forEach用表达式-> 操作List<对象>,如下:
if (!CollectionUtils.isEmpty(userList)){ userList.forEach(userObj-> { //在此循环里,操作循环 出来的对象 }); }
4、将list<对象>转成Map
// nn_navigation表的子类目数据 转成map Map<Long, NavigationDO> navigationMap = navigationDOS.stream().collect(Collectors.toMap(NavigationDO::getId, Function.identity(), (key1, key2) -> key1)); //把map的key转成String类型 Map<String, NavigationDO> navigationMap2 = navigationMap.entrySet().stream().collect(Collectors.toMap( entry -> entry.getKey().toString(), Map.Entry::getValue));
5、Map<String, Student>对象,转成 List<Student>数据
//先从缓存取
Map<String, ItemBaseInfo> thirdStateCacheMap = (Map<String, ItemBaseInfo>) cacheManager.batchGetAsMap(keyList);
//缓存中取到的map集合转成List<>对象,并且过滤掉value为null的空数据 itemBaseInfoList = thirdStateCacheMap.values().stream().filter(Objects::nonNull).collect(Collectors.toList());
6、list使用stream过滤条件取数据
//========================================================================list取数据
Person p = new Person();
p.setName("aaa");
p.setId(1);
Person p2 = new Person();
p2.setName("bbb");
p2.setId(2);
List<Person> pList = new ArrayList<Person>();
pList.add(p);
pList.add(p2);
List<Person> ps = pList.stream().filter(a -> a.getName().equals("bbb") && a.getId() == 2).collect(Collectors.toList());
ps.forEach(System.out::println);
7、一个List<Student>集合进行id排序,id是Long类型,并且有null值,从小到大排,空值排最后
students.sort(Comparator.comparing(Student::getId, Comparator.nullsFirst(Comparator.naturalOrder())));
8,List<Student>对象,从小到大,null排最后,Integer类型
List<People> peopleArrayList = new ArrayList<>();
People p1 = new People("Alice", 30L, 1);
People p2 = new People("Bob", 25L, null);
People p3 = new People("Alice2", 35L, 3);
People p4 = new People("Charlie", 30L, 4);
People p5 = new People("Bob", 22L, null);
People p6 = new People("Bob2", 27L, 3);
peopleArrayList.add(p1);
peopleArrayList.add(p2);
peopleArrayList.add(p3);
peopleArrayList.add(p4);
peopleArrayList.add(p5);
peopleArrayList.add(p6);
peopleArrayList.sort((o1, o2) -> { Integer v1 = o1.getBaseSort(); Integer v2 = o2.getBaseSort(); if (v1 == null && v2 == null) return 0; // 如果两个都是null,则认为相等 if (v1 == null) return 1; // 将null排在最后 if (v2 == null) return -1; // 将null排在最后,所以这里是-1而不是1(相对于第一种方法) return v1.compareTo(v2); // 正常比较非null值 });
。
.

浙公网安备 33010602011771号