java - Streams Collections.toMap() from List . How to keep the order? -
i creating map list follows :
map<string,itemvariant> map = itemext.getvariants() .stream().map((extvar)->{ //convert variant itemvariant itemvar = conversionservice.convert(extvar, itemvariant.class); return itemvar; }).collect(collectors.tomap(itemvariant::getsku, function.<itemvariant>identity()));
i want keep same order in list: itemext.getvariants()
how create linkedhashmap using these collectors.tomap() functions ?
the 2 parameter version of collectors.tomap()
following:
public static <t, k, u> collector<t, ?, map<k,u>> tomap( function<? super t, ? extends k> keymapper, function<? super t, ? extends u> valuemapper) { return tomap(keymapper, valuemapper, throwingmerger(), hashmap::new); }
so can replace:
collectors.tomap(itemvariant::getsku, function.<itemvariant>identity())
with:
collectors.tomap(itemvariant::getsku, function.<itemvariant>identity(), (u, v) -> { throw new illegalstateexception(string.format("duplicate key %s", u)); }, linkedhashmap::new)
or make bit cleaner, write new tolinkedmap() method:
public class morecollectors { public static <t, k, u> collector<t, ?, map<k,u>> tolinkedmap( function<? super t, ? extends k> keymapper, function<? super t, ? extends u> valuemapper) { return collectors.tomap(keymapper, valuemapper, (u, v) -> { throw new illegalstateexception(string.format("duplicate key %s", u)); }, linkedhashmap::new); } }
and use that.
Comments
Post a Comment