java - Process list stream and collect into map/ImmutableMap with only non null values -
how process list of string , collec map or immutable map value 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();
please tell, there better way achieve via collect?
if have access apache commons library can make use of 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 practice make special data classes describes mapping item->result more specificly
here example, create class this:
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 that:
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)))
you can read here why google gave idea of tuples , pairs , don't use them in cases
if after don't want use other class can leverage api of optional:
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();
Comments
Post a Comment