3

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

2
  • 4
    You'll have to work with List<List<String>> instead of List<String[]>, since arrays don't override Object's equals. Commented Nov 18, 2016 at 20:44
  • Got it working! Thanks you. Commented Nov 19, 2016 at 0:12

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.