Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove duplicates from ArrayList<String[]> - java

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

like image 394
QuebecSquad Avatar asked Jun 13 '26 09:06

QuebecSquad


1 Answers

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

like image 185
Andy Turner Avatar answered Jun 15 '26 22:06

Andy Turner