我们可以使用Stream API来删除List中的重复元素。具体步骤如下: 代码语言:txt AI代码解释 List<String> listWithDuplicates = Arrays.asList("apple", "banana", "orange", "apple", "pear", "banana"); List<String> listWithoutDuplicates = listWithDuplicates.stream().distinct().collect(Collectors.toList...
asList(1, 1, 2, 3, 3, 3, 4, 5, 6, 6, 6, 7, 8)); System.out.println(numbersList); LinkedHashSet<Integer> hashSet = new LinkedHashSet<>(numbersList); ArrayList<Integer> listWithoutDuplicates = new ArrayList<>(hashSet); System.out.println(listWithoutDuplicates); } } 输出: ...
ArrayList<Integer> numbersList =newArrayList<>(Arrays.asList(1, 1, 2, 3, 3, 3, 4, 5, 6, 6, 6, 7, 8)); System.out.println(numbersList); LinkedHashSet<Integer> hashSet =newLinkedHashSet<>(numbersList); ArrayList<Integer> listWithoutDuplicates =newArrayList<>(hashSet); System.out.p...
结果ArrayList不包含重复的整数。 ArrayList<Integer> numbersList = new ArrayList<>(Arrays.asList(1, 1, 2, 3, 3, 3, 4, 5, 6, 6, 6, 7, 8)); LinkedHashSet<Integer> hashSet = new LinkedHashSet<>(items); ArrayList<Integer> listWithoutDuplicates = new ArrayList<>(hashSet); System.out...
List<String> listWithoutDuplicates = new ArrayList<>(setWithoutDuplicates);在这个例子中,我们首先创建了一个包含重复元素的List。然后,我们将该List传递给一个新的HashSet实例,这将自动删除重复项。最后,我们将HashSet转换回List以获得没有重复项的列表。方法2: 使用LinkedHashSet LinkedHashSet是一种有序的...
List<String> listWithoutDuplicates =newArrayList<>(set); 二、利用Java 8的Stream API Java 8引入了Stream API,提供了一种更加函数式的方式来处理集合。我们可以使用Stream的distinct()方法来轻松地去除重复项。 原理解析 distinct()方法是Stream接口的一个中间操作,它会过滤掉流中的重复元素。
ArrayList<Integer> listWithoutDuplicates = new ArrayList<>(hashSet); System.out.println(listWithoutDuplicates
assertThat(listWithoutDuplicates, hasSize(5)); assertThat(listWithoutDuplicates, containsInRelativeOrder(5, 0, 3, 1, 2)); } 上面的代码在将重复删除后还是会保持顺序不变的。 使用Guava 删除重复元素 我们可以使用 Guava 完成上面一样的操作:
将Stream转换回List。 下面是使用Java 8的Stream API去除List中重复对象的示例代码: importjava.util.*;publicclassRemoveDuplicatesUsingStream{publicstaticvoidmain(String[]args){List<String>listWithDuplicates=Arrays.asList("apple","banana","apple","orange","banana");List<String>listWithoutDuplicates=listWit...
List without duplicates: [banana, orange, apple] 1. 2. 可以看到,通过Set的特性,将List中的重复元素去掉了。 2. 自定义保留元素 有时候,我们不仅需要去重List,还需要根据特定的条件自定义保留哪些元素。在这种情况下,我们可以使用Java的流(Stream)来实现。