温馨提示×

Java中list.stream方法的去重操作有哪些

小樊
92
2024-08-13 12:22:36
栏目: 编程语言

在Java中,可以使用list.stream().distinct()方法来进行去重操作,该方法会返回一个去除重复元素的流。此外,还可以结合使用Collectors.toSet()或Collectors.toMap()方法来实现去重操作。具体示例如下:

  1. 使用distinct()方法:
List<Integer> list = Arrays.asList(1, 2, 3, 1, 2, 4);
List<Integer> distinctList = list.stream().distinct().collect(Collectors.toList());
System.out.println(distinctList); // 输出 [1, 2, 3, 4]
  1. 使用Collectors.toSet()方法:
List<Integer> list = Arrays.asList(1, 2, 3, 1, 2, 4);
Set<Integer> distinctSet = list.stream().collect(Collectors.toSet());
System.out.println(distinctSet); // 输出 [1, 2, 3, 4]
  1. 使用Collectors.toMap()方法:
List<Integer> list = Arrays.asList(1, 2, 3, 1, 2, 4);
Map<Integer, Integer> distinctMap = list.stream().collect(Collectors.toMap(Function.identity(), Function.identity(), (e1, e2) -> e1));
System.out.println(distinctMap.keySet()); // 输出 [1, 2, 3, 4]

0