Programing

최신 Java와 배열 목록의 동일성을 비교하는 방법은 무엇입니까?

lottogame 2020. 11. 8. 09:08
반응형

최신 Java와 배열 목록의 동일성을 비교하는 방법은 무엇입니까?


두 개의 배열 목록이 있습니다.

외부 라이브러리를 사용하지 않고 Java 8 및 해당 기능과 이들의 동등성을 어떻게 쉽게 비교할 수 있습니까? 나는 다음과 같은 무차별 대입 코드보다 "더 나은"(높은 수준, 더 짧고, 더 효율적인) 솔루션을 찾고 있습니다 (질문의 요지가 아닌 오타 등을 포함 할 수없는 코드가 없을 수 있음).

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;
}

또는 더 좋은 방법이 없다면 그것도 유효한 대답입니다.

보너스 : Java 9가 Java 8이 제공 할 수있는 것보다 더 나은 방법을 제공한다면 자유롭게 언급하십시오.

편집 : 주석을보고이 질문이 얼마나 뜨거워 졌는지 확인한 후 " 더 나은 "은 배열 내용을 확인하기 전에 먼저 모든 배열의 길이를 확인하는 것을 포함해야 한다고 생각 합니다. 내부의 경우 불평등을 훨씬 더 빨리 찾을 수 있기 때문입니다. 배열이 깁니다.


1) Java 8 스트림 기반 솔루션 :

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 이상에서 작동) :

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

3) 새 요구 사항 (포함 된 문자열 배열 길이를 먼저 확인하기 위해 ) 과 관련하여 변환 된 목록에 대한 동등성 검사를 수행하는 일반 도우미 메서드를 작성할 수 있습니다.

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

for적어도 루프로 이어지는 streamified 할 수 있습니다 :

return (list1.size()==list2.size() &&
        IntStream.range(0, list1.size())
                 .allMatch(i -> Arrays.equals(list1.get(i), list2.get(i)));

사용하여 zip(여기서 람다 B93에서 유래)으로부터 기능 https://stackoverflow.com/a/23529010/755183 코드가 같을 수있다 :

boolean match = a.size() == b.size() && 
                zip(a.stream(), b.stream(), Arrays::deepEquals).
                allMatch(equal -> equal)

최신 정보

배열의 크기를 먼저 확인한 다음 내용을 확인하려면 고려할 솔루션이 될 수 있습니다.

final boolean match = a.size() == b.size() 
                   && zip(a.stream(), b.stream(), (as, bs) -> as.length == bs.length).
                      allMatch(equal -> equal)
                   && zip(a.stream(), b.stream(), Arrays::deepEquals).
                      allMatch(equal -> equal);

당신은 (호출이되도록리스트는 랜덤 액세스리스트 인 경우 스트림을 사용하는 get빠른 - 일반적으로 일정 시간)로 이어지는 :

//checks for null and size before
boolean same = IntStream.range(0, list1.size()).allMatch(i -> Arrays.equals(list1.get(i), list2.get(i)));

그러나 그렇지 않은 일부 구현 (예 : LinkedLists)을 매개 변수로 제공 할 수 있습니다. 이 경우 가장 좋은 방법은 반복기를 명시 적으로 사용하는 것입니다. 다음과 같은 것 :

boolean compare(List<String[]> list1, List<String[]> list2) {

    //checks for null and size

    Iterator<String[]> iteList1 = list1.iterator();
    Iterator<String[]> iteList2 = list2.iterator();

    while(iteList1.hasNext()) {
        if(!Arrays.equals(iteList1.next(), iteList2.next())) {
            return false;
        }
    }
    return true;
}

반복기를 사용하여 한 목록을 스트리밍하고 다른 목록의 각 요소와 비교할 수 있습니다.

Iterator<String[]> it = list1.iterator();
boolean match = list1.size() == list2.size() &&
                list2.stream().allMatch(a -> Arrays.equals(a, it.next()));

get(index)첫 번째 목록 메서드 대신 반복기를 사용하는 것이 목록이 있는지 여부는 중요하지 않기 때문에 더 좋습니다 RandomAccess.

Note: this only works with a sequential stream. Using a parallel stream will lead to wrong results.


EDIT: As per the question last edit, which indicates it would be better to check the length of every pair of arrays in advance, I think it could be achieved with a slight modification to my previous code:

Iterator<String[]> itLength = list1.iterator();
Iterator<String[]> itContents = list1.iterator();

boolean match = 
        list1.size() == list2.size()
    && 
        list2.stream()
            .allMatch(a -> {
                String[] s = itLength.next();
                return s == null ? a == null :
                       a == null ? s == null :
                       a.length == s.length;
            })
    && 
        list2.stream()
            .allMatch(a -> Arrays.equals(a, itContents.next()));

Here I'm using two iterators and am streaming list2 twice, but I see no other way to check all lengths before checking the contents of the first pair of arrays. Check for lengths is null-safe, while check for contents is delegated to the Arrays.equals(array1, array2) method.

참고URL : https://stackoverflow.com/questions/35408290/how-to-compare-equality-of-lists-of-arrays-with-modern-java

반응형