I want to remove duplicate from an ArrayList.
If I do this, its working:
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());
But if I want to remove duplicate String[] instead of String, its not removing duplicates:
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;
Any solution to fix this or another way to remove duplicate of an ArrayList<String[]>? Thanks
As @Eran notes, you can't work with arrays directly, since they don't override Object.equals(). Hence, arrays a and b are only equal if they are the same instance (a == b).
It's straightforward to convert the arrays to Lists, which do override 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());
Ideone demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With