如何在Java 8中按值过滤地图? [英] How to filter a map by its values in Java 8?

查看:65
本文介绍了如何在Java 8中按值过滤地图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个映射,其中的值是字符串,键是列表:Map<String, List<BoMLine>> materials. 我想用它的值来过滤这张地图.像这样的东西:

I have a map where the values are strings and the keys are lists: Map<String, List<BoMLine>> materials. I'd like to filter this map by its values; something like this:

materials.entrySet().stream()
       .filter(a->a.getValue().stream()
           .filter(l->MaterialDao.findMaterialByName(l.getMaterial()).ispresent)

但这对我不起作用.有人有主意吗?

But it's not working for me. Does anybody have an idea?

谢谢.

推荐答案

如果我正确理解了过滤条件,则要检查从值List生成的过滤后的Stream是否包含任何元素,如果有的话,将相应的Map条目传递到输出Map.

If I understand your filtering criteria correctly, you want to check if the filtered Stream you produced from the value List has any elements, and if so, pass the corresponding Map entry to the output Map.

Map<String, List<BoMLine>>
    filtered = materials.entrySet()
                        .stream()
                        .filter(a->a.getValue()
                                    .stream()
                                    .anyMatch(l->MaterialDao.findMaterialByName(l.getMaterial())))
                        .collect(Collectors.toMap(e->e.getKey(),e->e.getValue()));

这是假设MaterialDao.findMaterialByName(l.getMaterial())返回boolean.

这篇关于如何在Java 8中按值过滤地图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆