package com.svnlan.order.controller; import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.stream.Collectors; public class TestClass { public static void main(String[] args) { User user1 = new User(5, "aa"); User user2 = new User(2, "ba"); User user3 = new User(3, "ac"); User user4 = new User(1, "aad"); User user5 = new User(4, "asd"); List<User> userList = Arrays.asList(user1, user2, user3, user4, user5); //获取所有ID集合 List<Integer> idList = userList.stream().map(User::getId).collect(Collectors.toList()); //排序ID List<User> userList1 = userList.stream().sorted(Comparator.comparingInt(User::getId)).collect(Collectors.toList()); //分组 Map<String, Long> map = userList.stream().collect(Collectors.groupingBy(User::getName, Collectors.counting())); //获取id大于2的 List<User> userList2 = userList.stream().filter(user -> user.getId() > 2).collect(Collectors.toList()); //获取最大 Integer id = userList.stream().map(User::getId).max(Integer::compareTo).get(); //获取最小 Integer id1 = userList.stream().map(User::getId).min(Integer::compareTo).get(); //获取id数量 long count = userList.stream().map(User::getId).count(); //总和 int sum = userList.stream().mapToInt(User::getId).sum(); //获取平均值 double d = userList.stream().mapToInt(User::getId).average().getAsDouble(); //匹配findAny/allMatch/noneMatch多用来判断 User user = userList.stream().findAny().get(); //获取第一个对象 User user6 = userList.stream().findFirst().get(); //将名字全转换为大写 List<String> list = userList.stream().map(User::getName).map(String::toUpperCase).collect(Collectors.toList()); //获取忽略第一个并取前几条数据 List<User> list1 = userList.stream().skip(1).limit(2).collect(Collectors.toList()); //去重 List<User> collect = userList.stream().distinct().collect(Collectors.toList()); } }
Java Lambda常用方法(持续更新)
最新推荐文章于 2024-09-11 20:25:27 发布