Java8 新特性Stream的使用

筛选

1.筛选年龄大于等于7的学生对象集合

List<Student> collect1 = studentList.stream().filter(a -> a.getAge() >= 7).collect(Collectors.toList());

2.筛选年龄大于等于7的学生的姓名集合

List<String> collect2 = studentList.stream().filter(a -> a.getAge() >=     7).map(Student::getName).collect(Collectors.toList());

3.根据某个字段去重

List<String> msgs = msgs.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Student:: getAge()))), ArrayList::new));

4.过滤字段为null的数据

userIdList = userIdList.stream().filter(userId -> userService.get(userId) != null
).collect(Collectors.toList());

5.字符串集合进行简单的去重(其他数据类型去重一样)

List<String> stringList = Arrays.asList("伽罗", "貂蝉", "芈月", "伽罗");

// jdk1.8Stream来去重
stringList = stringList.stream().distinct().collect(Collectors.toList());
System.out.println(JSON.toJSONString(stringList));

// 执行结果:["伽罗","貂蝉","芈月"]

JSONObject 根据某个字段去重

ListVO<JSONObject> formDataPage = formRemoteService.getFormDataPage();
List<Map<String, Object>> list2 = formDataPage.getList().stream().collect(
        Collectors.collectingAndThen(
                Collectors.toCollection(
                        () ->new TreeSet<>(Comparator.comparing(m->m.get("value").toString()))
                ),ArrayList::new
        )
);



 List<Map<String,Object>> list1 = new ArrayList<>();  
 Map<String,Object> map = new HashMap();
 Map<String,Object> map2 = new HashMap();

 map.put("key","1");
 map.put("value","a");
 map2.put("key","2");
 map2.put("value","a");

 list1.add(map);
 list1.add(map2);
 list1.forEach(System.out::println);
 List<Map<String, Object>> list2 = list1.stream().collect(
         Collectors.collectingAndThen(
                 Collectors.toCollection(
                         () ->new TreeSet<>(Comparator.comparing(m->m.get("value").toString()))
                 ),ArrayList::new
         )
 );
 System.out.println("--------");
 list2.forEach(System.out::println);

6.获取对象集合中单独某个字段的List集合&Set集合

//根据某个字段获取单独的List集合
List idNoList = List.stream().map(Fduser::getIdNo).collect(Collectors.toList());

//根据某个字段获取单独的Set集合
Set idNoSet = List.stream().map(Fduser::getIdNo).collect(Collectors.toSet());
@Data
public class Student {

    private String name;

    private Integer age;

    private String sex;

    private String grade;
    
    public Student(String name, Integer age, String sex, String grade) {
        this.name = name;
        this.age = age;
        this.sex = sex;
        this.grade = grade;
    }
}
public static void main(String[] args) {
List<Student> studentList = new ArrayList<Student>();
studentList.add(new Student("Tom1", 5, "男", "一年级"));
studentList.add(new Student("Tom2", 6, "女", "二年级"));
studentList.add(new Student("Tom3", 7, "女", "三年级"));
studentList.add(new Student("Tom4", 5, "女", "三年级"));
studentList.add(new Student("Tom5", 6, "男", "二年级"));
studentList.add(new Student("Tom6", 8, "男", "一年级"));

//筛选年龄大于等于7的学生信息
List<Student> collect1 = studentList.stream().filter(a -> a.getAge() >= 7).collect(Collectors.toList());

//筛选年龄大于等于7的学生的姓名
 List<String> collect2 = studentList.stream().filter(a -> a.getAge() >=     7).map(Student::getName).collect(Collectors.toList());
    
//根据某个字段去重
List<String> msgs = msgs.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Student:: getAge()))), ArrayList::new));

//字符串集合进行简单的去重(其他数据类型去重一样)
List<String> stringList = Arrays.asList("伽罗", "貂蝉", "芈月", "伽罗");
//jdk1.8Stream来去重
stringList = stringList.stream().distinct().collect(Collectors.toList());
System.out.println(JSON.toJSONString(stringList));
/**
 * 执行结果:["伽罗","貂蝉","芈月"]
 */

//根据某个字段获取单独的List集合
List idNoList = List.stream().map(Fduser::getIdNo).collect(Collectors.toList());

//根据某个字段获取单独的Set集合
Set idNoSet = List.stream().map(Fduser::getIdNo).collect(Collectors.toSet());


//过滤为null的数据
userIdList = userIdList.stream().filter(userId -> userService.get(userId) != null
).collect(Collectors.toList());

}

分组

1.按照集合中的某个字段条件进行Boolean类型分组

partitioningBy 返回值Map<Boolean, List>,key是Boolean类型,只能分两组

Map<Boolean, List<Student>> age = studentList.stream().collect(Collectors.partitioningBy(x -> x.getAge() > 6));

2.按照集合中的某个字段进行条件分组

groupingBy 可以根据各种属性进行分组,分组个数不受限制,并且可以分组后统计个数

Map<String, List<Student>> group = studentList.stream().collect(Collectors.groupingBy(Student::getSex));

3.按学生年级分组,再按性别分组

Map<String, Map<String, List<Student>>> group2 = studentList.stream().collect(Collectors.groupingBy(Student::getGrade,  Collectors.groupingBy(Student::getSex)));

4.分组并排序(自然排序)

TreeMap<Integer, List<SubmitMultiDeployRequest>> treeMap = request.stream().collect(Collectors.groupingBy(SubmitMultiDeployRequest::getPriority, TreeMap::new, Collectors.toList()));
public static void main(String[] args) {
   /**
    * 分组
    */
   List<Student> studentList = new ArrayList<Student>();
   studentList.add(new Student("Tom1", 5, "男", "一年级"));
   studentList.add(new Student("Tom2", 6, "女", "二年级"));
   studentList.add(new Student("Tom3", 7, "女", "三年级"));
   studentList.add(new Student("Tom4", 5, "女", "三年级"));
   studentList.add(new Student("Tom5", 6, "男", "二年级"));
   studentList.add(new Student("Tom6", 8, "男", "一年级"));

   // 学生年龄大于6的分组
   Map<Boolean, List<Student>> age = studentList.stream().collect(Collectors.partitioningBy(x -> x.getAge() > 6));

   // 学生性别分组
   Map<String, List<Student>> group = studentList.stream().collect(Collectors.groupingBy(Student::getSex));

   // 学生年级分组,再按性别分组
   Map<String, Map<String, List<Student>>> group2 = studentList.stream().collect(Collectors.groupingBy(Student::getGrade,  Collectors.groupingBy(Student::getSex)));

   // 查找性别男年的所对应的年龄
   Map<String, String> group3 = studentList.stream().filter(i -> i.getSex().equals("男")).collect(
   Collectors.toMap(Student::getName, Student::getSex));

   // 根据性别获取年龄集合
   Map<String, List<Integer>> group5 = studentList.stream().collect(
         Collectors.groupingBy(Student::getSex, Collectors.mapping(Student::getAge, toList())));
   
   /**
    * 分别从每个年级中抽取一个人
    * 处理之前:
    * [Student(name=Tom1, age=5, sex=男, grade=一年级),
    * Student(name=Tom2, age=6, sex=女, grade=二年级),
    * Student(name=Tom3, age=7, sex=女, grade=三年级),
    * Student(name=Tom4, age=5, sex=女, grade=三年级),
    * Student(name=Tom5, age=6, sex=男, grade=二年级),
    * Student(name=Tom6, age=8, sex=男, grade=一年级)]
    *
    * 处理之后:
    * {一年级=Student(name=Tom1, age=5, sex=男, grade=一年级),
    * 三年级=Student(name=Tom3, age=7, sex=女, grade=三年级),
    * 二年级=Student(name=Tom2, age=6, sex=女, grade=二年级)}
    */
   Map<String, Student> group6 = studentList.stream().collect(Collectors.toMap(Student::getGrade, Function.identity(), (nowValue, newValue) -> nowValue));



Map<String, Student> map = list.stream().collect(Collectors.toMap(Student::getGrade,Function.identity()));



//分组并排序(自然排序)
TreeMap<Integer, List<SubmitMultiDeployRequest>> treeMap = request.stream().collect(Collectors.groupingBy(SubmitMultiDeployRequest::getPriority, TreeMap::new, Collectors.toList()));


}

排序

1.按某个字段进行升序

//升序
System.out.println("升序:");
List<student> collectStudentSorted = students.stream().sorted(Comparator.comparing(student::getScore)).collect(Collectors.toList());
collectStudentSorted.stream().forEach(System.out::println);

2.按某个字段进行降序

//降序
System.out.println("降序:");
List<student> collectStudentSortedDesc = students.stream().sorted(Comparator.comparing(student::getScore).reversed()).collect(Collectors.toList());
collectStudentSortedDesc.stream().forEach(System.out::println);

转换

1.将一个对象集合转换成另一个对象集合

//从数据库查出来的数据
List<UserAccount> list = userService.list();

//需要转为UserAccountVo
List<UserAccountVO> userAccountVOList = list.stream().map(UserAccount -> {
    UserAccountVO userAccountVo = new UserAccountVO();
    BeanUtils.copyProperties(UserAccount, userAccountVo);
    return userAccountVo;
}).collect(Collectors.toList());

2.将字符串按逗号分隔组成集合

String authIds = "1,2,3,4,5,6,7,8";
List<Long> idList = (List)Arrays.stream(authIds.split(",")).map((ele) -> {
         return Long.valueOf(ele);
}).collect(Collectors.toList());

求和

1.BigDecimal 类型分组求和

private static List<Apple> list = new ArrayList<>();
list.add(Apple.builder().id(1).name("苹果1").price(new BigDecimal("1")).build());
list.add(Apple.builder().id(2).name("苹果2").price(new BigDecimal("2")).build());
list.add(Apple.builder().id(3).name("苹果3").price(new BigDecimal("3")).build());

BigDecimal totalPrice = list.stream().map(Apple::getPrice).reduce(BigDecimal.ZERO, BigDecimal::add);
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值