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

3

我希望从ArrayList中删除重复项。

如果我这样做,它可以工作:

    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());

但是,如果我想移除重复的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;

有没有解决这个问题的方法或者另一种去除 ArrayList<String[]> 中重复元素的方式?谢谢。

4
你需要使用List<List<String>>代替List<String[]>,因为数组不会覆盖Object的equals方法。 - Eran
搞定了!谢谢你。 - QuebecSquad
1个回答

4

正如@Eran所指出的,你不能直接处理数组,因为它们不会覆盖Object.equals()。 因此,只有当它们是同一实例(a == b)时,数组ab才相等。

将数组转换为List很简单,因为它们确实覆盖了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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接