[英]Streams, check that two lists of objects has same nested lists of another objects
我有我檢查的日志事件列表,它們應該是相同的。 有Event對象的結構:
public class Event {
public String type;
public List<Item> items;
public Event(String type, List<Item> items) {
this.type = type;
this.items = items;
}
}
public class Item {
public String id;
public String value;
public Item(String id, String value) {
this.id = id;
this.value = value;
}
}
讓我們填充“應該”對象,“真實”對象並檢查它們是否具有相同的項目
List<Event> should = asList(
new Event("1000", asList(new Item("server_id", "1"), new Item("user_id", "11"))),
new Event("1000", asList(new Item("server_id", "1"), new Item("user_id", "11"))));
List<Event> logged = asList(
new Event("1000", asList(new Item("server_id", "1"), new Item("user_id", "11"))),
new Event("1000", asList(new Item("server_id", "1"), new Item("user_id", "11"))));
boolean logMatch = logged.stream()
.allMatch(e1 ->
should.stream()
.allMatch(e2 -> e2.items
.stream()
.allMatch(a2 -> e1.items
.stream()
.anyMatch(a1 -> a1.value.equals(a2.value)))));
System.out.println(logMatch);
這是真的,但我有一個問題,如果我將“應該”的任何值改為“11”,我會成真的。 我該如何解決這個問題或如何使這種比較更簡單?
您的問題是,您只是檢查每個logged
元素是否至少在should
列表中具有相同value
的元素。 您更願意檢查兩個value
集合是否相同。
在這種情況下,簡單的更正可以使用列表比較:
List<String> actualValues = logged.stream().flatMap(l -> l.items.stream())
.map(i -> i.value).collect(Collectors.toList());
List<String> shouldValues = should.stream().flatMap(l -> l.items.stream())
.map(i -> i.value).collect(Collectors.toList());
boolean logMatch = actualValues.equals(shouldValues);
這種比較是嚴格的,並考慮到了順序。 如果您寧願忽略元素的順序,則可以收集以設置為忽略項目的順序。
編輯:如果您需要檢查多個字段,您可以比較實際事件。 以下使用謂詞:
List<Item> actualValues = logged.stream().flatMap(l -> l.items.stream())
.collect(Collectors.toList());
List<Item> shouldValues = should.stream().flatMap(l -> l.items.stream())
.collect(Collectors.toList());
BiPredicate<Item, Item> predicate = (item1, item2) -> item1.id.equals(item2.id)
&& item1.value.equals(item2.value);
boolean res = actualValues.size() == shouldValues.size() //should be same length
&& IntStream.range(0, actualValues.size())
.filter(i -> !predicate.test(actualValues.get(i), shouldValues.get(i)))
.count() == 0; //all elements's ID and value must match
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.