如何处理字符串列表并将其仅对存在值的用户集合为Map或Immutable map
String anotherParam = "xyz";
Map.Builder<String,String> resultMap = ImmutableMap.builder(..)
listOfItems.stream()
.filter(Objects::nonNull)
.distinct()
.forEach(
item -> {
final Optional<String> result =
getProcessedItem(item,anotherParam);
if (result.isPresent()) {
resultMap.put(item, result.get());
}
});
return resultMap.build();
请告诉我们,有没有一种更好的方法可以通过收集来实现这一目标?
如果您有权访问Apache Commons库,则可以使用Pair.class
Map<String, String> resultMap = ImmutableMap.copyof(listOfItems()
.stream()
.filter(Objects::nonNull)
.distinct()
.map(it -> Pair.of(it, getProcessedItem(it,anotherParam))
.filter(pair -> pair.getValue().isPresent())
.collect(toMap(Pair::getKey, pair -> pair.getValue().get())))
但是,做一个特殊的数据类来描述映射项->结果是一个很好的习惯
这是一个示例,创建这样的类:
static class ItemResult(){
public final String item;
public final Optional<String> result;
public ItemResult(String item, Optional<String> result){
this.item = item;
this.result = result;
}
public boolean isPresent(){
return this.result.isPresent();
}
public String getResult(){
return result.get();
}
}
并像这样使用它:
Map<String, String> resultMap = ImmutableMap.copyOf(listOfItems()
.stream()
.filter(Objects::nonNull)
.distinct()
.map(it -> new ItemResult(it, getProcessedItem(it,anotherParam))
.filter(ItemResult::isPresent)
.collect(toMap(ItemResult::item, ItemResult::getResult)))
您可以在此处阅读为什么Google放弃元组和对的想法并且在大多数情况下不使用它们
如果毕竟您不想使用任何其他类,则可以使用Optional的api:
Map.Builder<String,String> resultMap = ImmutableMap.builder(..)
listOfItems.stream()
.filter(Objects::nonNull)
.distinct()
.forEach(item -> getProcessedItem(item,anotherParam)
.ifPresent(result -> resultMap.put(item result));
return resultMap.build();
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句