java8 stream流 (遍历、排序、分组、去重)

本文详细介绍了Java8 Stream流的使用,包括如何进行foreach遍历、通过Comparator进行排序、按单一或多个属性进行分组,以及利用distinct方法实现去重。在去重部分,特别强调了类需要实现hashcode()和equals()方法以确保正确性,并给出了基于特定属性去重的例子。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

遍历
  1. foreach遍历
    list.forEach(str-> System.out.println(str));

  2. 流遍历
    List list = new ArrayList();
    list.add(“a”);
    list.add(“b”);
    list.add(“c”);
    list.add(“d”);
    List list3 = new ArrayList();
    // 过滤字符串为a的元素
    list.stream().filter(str -> !“a”.equals(str)).forEach(str -> {
    list3.add(str);
    });
    System.out.println(list3);

排序
  1. 通过student的id进行排序
    List sortedIds = list.stream()
    .sorted(Comparator.comparingLong(student::getId))
    .collect(Collectors.toList());
分組

List list

  1. 通过单一属性(年龄)进行分组:
    Map<String, List> groupedMap =
    list.stream()
    .collect(Collectors.groupingBy(Student::getAge));
    得到的map集合中: key就是每一个age value就是每一个age对应的list

  2. 根据多个属性(年龄和性别)进行分组
    得到的集合是一个年龄下分为两种性别(嵌套调用groupby)
    Map<String, Map<String, List>> groupedMap = list.stream()
    .collect(Collectors.groupingBy(Student::getAge, Collectors.groupingBy(Student::getSex)));

  3. 根据组合属性(年龄和性别组合)进行分组
    private static String fetchGroupKey(Student student) {
    return student.getAge() + “_” + student.getSex();
    } //组合字段

    Map<String, List> groupedMap =
    list.stream()
    .collect(Collectors.groupingBy(d -> fetchGroupKey(d)));

去重
  1. 对于string列表去重
    List stringList;
    stringList = stringList.stream().distinct().collect(Collectors.toList());

  2. 对于实体类的去重
    List studentList;
    studentList = studentList.stream().distinct().collect(Collectors.toList());

distinct()方法是通过hashcode()和equals()方法来获取不同元素,因此需要去重的类必须实现hashcode()和equals()方法。同理也可以通过重写定制的hashcode()和equals()方法来达到某些特殊需求的去重。

  1. 根据 List 中 Object 某个属性去重(姓名去重)
    List studentList;
    studentList = studentList.stream()
    .collect(collectingAndThen(toCollection(()
    -> new TreeSet<>(Comparator.comparing(Student::getName))), ArrayList::new));

  2. 根据List 中 Object 多个属性去重(姓名,年龄去重)
    ListstudentList;
    studentList=studentList.stream()
    .collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(o -> o.getName() + “;” + o.getAge()))), ArrayList::new));

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值