List<User> userList = new ArrayList<>();
userList.add(new User(1,"zhangsan","123","男"));
userList.add(new User(2,"lisi","234", "男"));
userList.add(new User(3,"one","123","女"));
userList.add(new User(4,"demo","123", "男"));
//1、foreach
userList.stream().forEach(System.out::println); (可能被替代)
userList.forEach(System.out::println)
//2、filter(查询性别为男的数据)
List<User> list = userList.stream().filter(e -> e.getGender().equals("男")).collect(Collectors.toList());
//3、findFirst
Optional<User> first = userList.stream().filter(e -> e.getGender().equals("女")).findFirst();
if(first.isPresent()){
User user = first.get();
}
//4、toSet
Set<User> collect = userList.stream().filter(e -> e.getGender().equals("男")).collect(Collectors.toSet());
collect.forEach(System.out::println);
//5、去重(根据某个字段去重需要重写equals方法)
userList.stream().distinct().collect(Collectors.toList());
//6、查询前2条
userList.stream().limit(2).collect(Collectors.toList()).forEach(System.out::println);
//7、查询从第2条以后的数据(不包括第2条)
userList.stream().skip(2).collect(Collectors.toList()).forEach(System.out::println);
/**
* 8、
* anyMatch表示,判断的条件里,任意一个元素成功,返回true
* allMatch表示,判断条件里的元素,所有的都是,返回true
* noneMatch跟allMatch相反,判断条件里的元素,所有的都不是,返回true
*/
System.out.println(userList.stream().anyMatch(e -> e.getGender().equals("男")));
System.out.println(userList.stream().allMatch(e -> e.getGender().equals("男")));
System.out.println(userList.stream().noneMatch(e -> e.getGender().equals("男")));
//10、list 转 map
Map<String, String> map = userList.stream().collect(Collectors.toMap(User::getUsername, User::getPassword));
//11、针对重复key的 覆盖之前的value
Map<String, String> map1 = userList.stream().collect(Collectors.toMap(User::getUsername, User::getPassword,(k,v) -> v));
//12、排序(正序)
List<User> sortList = userList.stream().sorted(Comparator.comparing(User::getUsername)).collect(Collectors.toList());
// 倒序
List<User> reverseList = userList.stream().sorted(Comparator.comparing(User::getUsername).reversed()).collect(Collectors.toList());
reverseList.forEach(System.out::println);
//非 stream 排序
userList.sort(Comparator.comparing(User::getUsername));
//13 、实体类集合中取出其中一个字段的集合
List<Integer> roleIdList = roleGroupList.stream().map(SysRoleGroup::getRoleId).collect(Collectors.toList());
//14、分组
Map<Long, List<ShoppingCart>> collect = list.stream().collect(Collectors.groupingBy(ShoppingCart::getCategoryId));
JDK8:stream
最新推荐文章于 2025-06-23 20:59:12 发布