java stream的distinct可以对集合进行去重,举例如下:

package demo;

import java.util.ArrayList;
import java.util.List;

public class StreamDistinctDemo {

    public static void main(String[] args) {
        List<Integer> integerList = new ArrayList<>();
        integerList.add(1);
        integerList.add(2);
        integerList.add(3);
        integerList.add(4);
        integerList.add(5);
        integerList.add(3);
        integerList.add(3);
        integerList.forEach(e -> System.out.print(e));
        System.out.println("*********");
        integerList.stream().distinct().forEach(e -> System.out.print(e));
    }
}

打印结果如下:

1234533*********
12345
distinct()是一个中间操作,不是终止操作,如果需要获取去重后的集合,需使用终止操作如下:
integerList=integerList.stream().distinct().collect(Collectors.toList());

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-12-10
  • 2021-11-20
  • 2021-05-22
  • 2021-08-13
  • 2021-12-13
猜你喜欢
  • 2022-12-23
  • 2021-09-30
  • 2021-12-14
  • 2021-12-12
  • 2020-05-11
  • 2021-07-15
  • 2021-11-07
相关资源
相似解决方案