处理列表流并收集到仅包含非空值的map/ImmutableMap

2024-04-07

如何处理字符串列表并将其收集到 Map 或 Immutable 映射中(仅针对那些存在值的字符串)

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)))

你可以阅读here https://github.com/google/guava/wiki/IdeaGraveyard#tuples-for-n--2为什么 Google 放弃了元组和对的想法并且在大多数情况下不使用它们

如果你毕竟不想使用任何其他类,你可以利用可选的 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();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

处理列表流并收集到仅包含非空值的map/ImmutableMap 的相关文章

随机推荐