我的函数有两个字符串参数- "Pizza“和"Chips”。我想使用流返回作者的“食物”键的内容与这两个字符串相匹配。
List<String> collection = Arrays.asList("Pizza", "Chips");
private static List<Map<String, Object>> authors = Arrays.asList(
ImmutableMap.of("id", "author-1",
"firstName", "Adam",
"lastName", "Awldridge",
"foods", Arrays.asList("Pizza", "Chips")),
ImmutableMap.of("id", "author-2",
"firstName", "Bert",
"lastName", "Bruce",
"foods", Arrays.asList("Pizza", "Fish")),
... // other authors
);这是我对流的尝试:
return authors
.stream()
.filter(authors.stream()
.flatMap(author -> author.get("foods"))
.findAny(queryFoods))
.findFirst().orElse(null);我想返回的第一个作者谁的食物与我的查询。我认为主要的困难是组织数据-不幸的是,我不能让下面的铸造工作。
.flatMap(author -> (List<String>) author.get("foods"))而且,这可能会流到作者太多次(我应该在我刚刚创建的流上使用.filter )。
authors.stream()发布于 2019-06-22 00:14:27
在这里,你不能直接把食物的价值作为一个清单来对待。它只是一个物体。因此,首先需要执行check实例,如果它是List的实例,则可以检查它是否包含集合中的值。
Map<String,Object> firstAuthor = authors
.stream()
.filter(author -> {
Object foods = author.get("foods");
if(foods instanceof List) {
List foodsList = (List) foods;
return foodsList.containsAll(collection);
}
return false;
})
.findFirst().orElse(null);输出:{id=Auth-1,firstName=Adam,lastName=Awldridge,foods=Pizza,Chips}
如果存在所需的作者,上述代码将为您提供所需的作者,否则为空。在这里,我假设您希望检查作者是否拥有由您创建的集合对象中存在的所有食物项目。如果您只想检查其中的一个项,那么可以使用来自java.util.List的方法,而不是containsAll()方法。此外,您还必须遍历集合对象,以检查集合中的每个项。
发布于 2019-06-22 20:59:00
我会通过过滤流来解决这个问题:
Map<String,Object> author = authors.stream()
.filter(a -> a.containsKey("foods"))
.filter(a -> a.get("foods") instanceof List)
.filter(a -> ((List) a.get("foods")).containsAll(collection))
.findFirst().orElse(null);发布于 2019-06-21 22:31:53
也许这就是你想要的?
authors
.stream()
.filter(a -> a.get("foods").stream().anyMatch(x -> "Pizza".equals(x)))
.findFirst().orElse(null);https://stackoverflow.com/questions/56711048
复制相似问题