我想从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().distinct().collect(Collectors.toList());
但是,如果我想删除重复的String []而不是String,它不会删除重复的内容:
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;
解决此问题的另一种解决方案或删除ArrayList< String []>的另一种方法的解决方案?谢谢
解决方法:
正如@Eran所指出的,您不能直接使用数组,因为它们不会覆盖Object.equals().因此,数组a和b仅在它们是相同实例的情况下才相等(a == b).
将数组转换为Lists很简单,但确实会覆盖Object.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());