Stream the list of processes and collect in map / ImmutableMap with only non-zero values

How to process a list of lines and collect them in a Map or Immutable map only for those whose value is present

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

Tell me, is there a better way to achieve this by collecting?

+4
source share
1 answer

If you have access to the Apache Commons library, you can use 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())))

But it's good practice to create custom data classes that more accurately describe your display element -> result

Here is an example, create the class as follows:

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();
    }
}

And use it like this:

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

- , 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();
+4

Source: https://habr.com/ru/post/1652278/


All Articles