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
QuebecSquadQuebecSquad
asked Nov 18, 2016 at 20:41
1 Answer 1
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 List
s, 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());
answered Nov 18, 2016 at 21:04
Comments
lang-java
List<List<String>>
instead ofList<String[]>
, since arrays don't override Object's equals.