我有这个pojo(这是一个例子,不是真实的例子):

Book {
  String name;
  Map<String, String> properties;
}

以及它们的列表:
List<Book> library;

TheBook1, {["lang", "pt-br"],["type","romance"],["author","John"]}
TheBook2, {["lang", "en-US"],["type","fiction"],["author","Brian"],["translation","pt-br,es"}

假设我有一个图书馆藏书,并且有一张包含搜索条件的地图,例如:
Map<String, String> criteria = new HashMap<>();
criteria.put(BOOK_TYPE, "romance");
criteria.put(BOOK_LANG, "pt-br");

如何搜索图书馆信息流的过滤谓词,以搜索满足所提供条件的所有图书?现在,该匹配必须是键和值的完全字符串匹配。

像这样:
Set<Book> result = library.stream()
.filter(b-> b.getProperties() **????**)
.collect(Collectors.toSet());

最佳答案

您可以简单地拥有:

List<Book> books =
    library.stream()
           .filter(b -> b.properties.entrySet().containsAll(criteria.entrySet()))
           .collect(Collectors.toList());

这将通过仅保留属性包含所有给定条件的书籍来过滤书籍。使用 containsAll 完成检查,这意味着它将保留完全包含给定条件的属性(匹配项相等,因此键和值相等)。

10-07 17:09
查看更多