从ArrayList中删除重复项<;字符串[]>;-JAVA
我想从ArrayList中删除重复项 如果我这样做,它的工作:从ArrayList中删除重复项<;字符串[]>;-JAVA,java,arraylist,duplicates,Java,Arraylist,Duplicates,我想从ArrayList中删除重复项 如果我这样做,它的工作: List<String> test = new ArrayList<>(); test.add("a"); test.add("a"); //Removing test.add("b"); test.add("c"); test.add("c"); //Removing test.add("d"); test = test.stream().d
List<String> test = new ArrayList<>();
test.add("a");
test.add("a"); //Removing
test.add("b");
test.add("c");
test.add("c"); //Removing
test.add("d");
test = test.stream().distinct().collect(Collectors.toList());
List test=newarraylist();
测试。添加(“a”);
测试。添加(“a”)//移除
测试。添加(“b”);
测试。添加(“c”);
测试。添加(“c”)//移除
测试。添加(“d”);
test=test.stream().distinct().collect(Collectors.toList());
但是,如果我想删除重复字符串[]而不是字符串,则不会删除重复项:
List<String[]> test = new ArrayList<>();
test.add(new String[]{"a", "a"});
test.add(new String[]{"a", "a"}); // Not removing
test.add(new String[]{"b", "a"});
test.add(new String[]{"b", "a"}); // Not removing
test.add(new String[]{"c", "a"});
test.add(new String[]{"c", "a"}); // Not removing
test = test.stream().distinct().collect(Collectors.toList());
ArrayList<String[]> test2 = (ArrayList<String[]>) test;
List test=newarraylist();
add(新字符串[]{“a”,“a”});
test.add(新字符串[]{“a”,“a”});//不删除
add(新字符串[]{“b”,“a”});
test.add(新字符串[]{“b”,“a”});//不删除
add(新字符串[]{“c”,“a”});
test.add(新字符串[]{“c”,“a”});//不删除
test=test.stream().distinct().collect(Collectors.toList());
ArrayList test2=(ArrayList)测试;
是否有任何解决方案可以解决此问题或以其他方式删除重复的
ArrayList
?感谢@Eran注释中的,您不能直接使用数组,因为它们不会覆盖Object.equals()
。因此,数组a
和b
只有在它们是同一实例时才相等(a==b
)
将数组转换为列表
s很简单,它会覆盖对象。equals
:
List<String[]> distinct = test.stream()
.map(Arrays::asList) // Convert them to lists
.distinct()
.map((e) -> e.toArray(new String[0])) // Convert them back to arrays.
.collect(Collectors.toList());
List distinct=test.stream()
.map(数组::asList)//将它们转换为列表
.distinct()
.map((e)->e.toArray(新字符串[0])//将它们转换回数组。
.collect(Collectors.toList());
您必须使用
List
而不是List
,因为数组不会覆盖对象的相等项。它正常工作了!谢谢你。