简体   繁体   English

从ArrayList <String []>中删除重复项 - java

[英]Remove duplicates from ArrayList<String[]> - java

I want to remove duplicate from an ArrayList. 我想从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: 但是,如果我想删除重复的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;

Any solution to fix this or another way to remove duplicate of an ArrayList<String[]> ? 任何修复此方法或其他方法来删除ArrayList<String[]>副本的解决方案? Thanks 谢谢

As @Eran notes, you can't work with arrays directly, since they don't override Object.equals() . 正如@Eran所说,你不能直接使用数组,因为它们不会覆盖Object.equals() Hence, arrays a and b are only equal if they are the same instance ( a == b ). 因此,如果数组ab是相同的实例( a == b ),则它们只相等。

It's straightforward to convert the arrays to List s, which do override Object.equals : 将数组转换为List s是很简单的,它们覆盖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 Ideone演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM