简体   繁体   中英

Java streams compare property is equal between two lists and return true or false

class Pair {
    String key;
    String value;
}
List<Pair> list1 = Stream.of(
        new Pair("key1", "value1"),
        new Pair("key2", "value2")
    )
    .collect(Collections.toList());

List<Pair> list2 = Stream.of(
        new Pair("key1", "value2"),
        new Pair("key2", "value3")
    )
    .collect(Collections.toList());

I want to perform some changes in the values in list2 and then compare it to list1 .

I want to check if the property key has not changed in list2 for all items in the list in comparison with list1. Only value property can be changed in list2.

And that the number of items in list2 is the same as list1 list1.size() = list2.size()

I am trying to write a stream that returns a boolean but somewhere I must have been mistaken

list1.stream()
    .allMatch(pair2->  list2.stream()
        .anyMatch(pair->pair.getKey().equals(pair2.getKey())));
    // Need to add list size() comparison too

Update: I managed to write a stream like this, junit tests seem to work, although it does not compare items at the same index as ernest_k's answer.

   list1.stream()
        .allMatch(pair -> list2.stream()
            .anyMatch(pair2-> pair.getKey().equals(pair2.getKey()) ) && list1.size()== list2.size()
            ));

You can use:

boolean result = list1.size() == list2.size() && 
        IntStream.range(0, list1.size())
            .allMatch(i -> list1.get(i).getKey().equals(list2.get(i).getKey()));

As you have to compare the lists element by element, you can't use a nested stream as that (like in your example), would simply do a cartesian join and return true if each list1 element has any list2 element with the same key (whereas you want that comparison to be index-aware)

You may consruct a lookup table to refer original keys.

public static compareStates(List<Pair> original, List<Pair> current){
    
        Map<String,Pair> lookupTable= original.stream.collect(Collectors.toMap(x ->x.key,x->x));
    
        boolean hasElementChanged = current.stream().filter(pair -> !lookupTable.containsKey(pair.key)).count() >0;
    
        boolean hasCountChanged = original.length !=current.length;
    
        return hasCountChanged || hasElementChanged;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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