IMLC.ME

Java List 如何去重

去重嘛,就是 Set 咯。

List<Integer> list = List.of(1, 1, 2, 2, 3, 3, 4, 4);
Set<Integer> tmp = new HashSet<>(list);
List<Integer> newList = new ArrayList<>(tmp);

Stream API 也提供了 distinct() 方法,方便在流式操作中去重。

list.stream()
     .distinct()
     .collect(Collectors.toList());