本文介绍了如何比较数组列表与现代Java的相等性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个数组列表。

如何在不使用外部库的情况下轻松比较这些与Java 8及其功能的相等性?我正在寻找一个更好(更高级别,更短,更高效)的解决方案,而不是像这样的强力代码(未经测试的代码,可能包含错别字等,而不是问题的重点):

How do I easily compare equality of these with Java 8 and its features, without using external libraries? I am looking for a "better" (higher-level, shorter, more efficient) solution than brute-force code like this (untested code, may contain typos etc, not the point of the question):

boolean compare(List<String[]> list1, List<String[]> list2)
{
    // tests for nulls etc omitted
    if(list1.size() != list2.size()) {
       return false;
    }
    for(i=0; i<list1.size(); ++i) {
        if(!Arrays.equals(list1.get(i), list2.get(i))) {
            return false;
        }
    }
    return true;
}

或者,如果没有更好的方式,这也是一个有效的答案。

Or, if there isn't any nicer way, that's a valid answer too.

奖励:如果Java 9提供了更好的Java 8可以提供的方式,也可以随意提及。

Bonus: If Java 9 offers an even better way what whaterver Java 8 can offer, feel free to mention it as well.

编辑:在查看评论后,看到这个问题如何变得温和,我认为更好应首先包含在检查数组内容之前检查所有数组的长度,因为如果内部数组很长,那么有可能更快地找到不等式。

After looking at the comments, and seeing how this question has become moderately hot, I think the "better" should include first checking lengths of all arrays, before checking array contents, because that has potential to find inequality much quicker, if inner arrays are long.

推荐答案

1)基于Java 8流的解决方案:

1) Solution based on Java 8 streams:

List<List<String>> first = list1.stream().map(Arrays::asList).collect(toList());
List<List<String>> second = list2.stream().map(Arrays::asList).collect(toList());
return first.equals(second);

2)更简单的解决方案(适用于Java 5 +):

2) Much simpler solution (works in Java 5+):

return Arrays.deepEquals(list1.toArray(), list2.toArray());

3)关于你的新要求(检查包含的String数组长度)首先,你可以写一个通用的辅助方法,对变换后的列表进行相等检查:

3) Regarding your new requirement (to check the contained String arrays length first), you could write a generic helper method that does equality check for transformed lists:

<T, U> boolean equal(List<T> list1, List<T> list2, Function<T, U> mapper) {
    List<U> first = list1.stream().map(mapper).collect(toList());
    List<U> second = list2.stream().map(mapper).collect(toList());
    return first.equals(second);
}

然后解决方案可能是:

return equal(list1, list2, s -> s.length)
    && equal(list1, list2, Arrays::asList);

这篇关于如何比较数组列表与现代Java的相等性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 11:26