在Java中使用Collectors.toMap时,如何跳过向新映射添加条目?

在Java中使用Collectors.toMap时,如何跳过向新映射添加条目?,java,java-8,Java,Java 8,这是我的代码: HashMap<String, List<Foo.Builder>> strFooMap = new HashMap<>(); // add stuff to strFooMap and do other things return new HashMap<>(strFooMap.entrySet() .stream() .collect(Collectors.toMap(Entry::getKey,

这是我的代码:

HashMap<String, List<Foo.Builder>> strFooMap = new HashMap<>();
// add stuff to strFooMap and do other things
return new HashMap<>(strFooMap.entrySet()
    .stream()
    .collect(Collectors.toMap(Entry::getKey,
        entry -> entry
            .getValue()
            .stream()
            .filter(builder -> {
              // do some conditional stuff to filter
            })
            .map(builder -> {
              return builder.build();
            })
            .collect(Collectors.toList())
        )
    )
);
HashMap strFooMap=newhashmap();
//向strFooMap添加内容并执行其他操作
返回新的HashMap(strFooMap.entrySet()
.stream()
.collect(Collectors.toMap)(条目::getKey,
输入->输入
.getValue()
.stream()
.filter(生成器->{
//做一些条件筛选
})
.map(生成器->{
返回builder.build();
})
.collect(收集器.toList())
)
)
);

因此,有时,在执行
筛选之后,我的
列表中的所有项目都将被筛选出来。然后在我的最后一个
HashMap
中,我有一个类似这样的条目:
{“someStr”->[]}
。我想删除值为空列表的键值对。我该怎么做呢?在
.stream().collect(Collectors.toMap(…)
代码中是否可以执行此操作?谢谢

解决方案之一是在将结果收集到地图之前移动值转换。它使您能够过滤掉空值

 List<Foo> transformValue(List<Foo.Builder> value) {
     //original value transformation logic
 }

 <K,V> Entry<K,V> pair(K key, V value){ 
    return new AbstractMap.SimpleEntry<>(key, value);
 }

 strFooMap.entrySet().stream()
      .map(entry -> pair(entry.getKey(), transformValue(entry.getValue()))
      .filter(entry -> !entry.getValue().isEmpty())
      .collect(toMap(Entry::getKey, Entry::getValue));
列表值(列表值){
//原值转换逻辑
}
条目对(K键,V值){
返回新的AbstractMap.SimpleEntry(键,值);
}
strFooMap.entrySet().stream()
.map(entry->pair(entry.getKey(),transformValue(entry.getValue()))
.filter(条目->!entry.getValue().isEmpty())
.collect(toMap(条目::getKey,条目::getValue));

请提供更多信息,如
Foo.Builder
方法和返回类型。另外,为什么要将返回的映射复制到另一个
HashMap
?在收集之前,您会
过滤掉它?我对java(尤其是lambda)相当陌生,您能简要解释一下中间部分的意思吗?是一个带有Key,Value作为返回的泛型类吗?
pair
是一个帮助函数,用于构造Map.Entry对象。由于Entry是泛型的,所以我创建了这个函数,使其也是泛型的。有关泛型的更多信息,请参阅文档