hashmap - Java 8: Create tuples from Java List -
i looking use java 8s new features create key value pairs java list , insert map
consider list [1, 2, 3, 4]
i looking 2 tuples, [1, 2]
, [3, 4]
this code, idea of copied answer similar question
where going wrong? nothing added map.
intstream.range(1, list.size()) .filter(i -> + 1 % 2 == 0) .maptoobj(i -> new abstractmap.simpleentry<>(list.get(i - 1), list.get(i))) .foreach(entry -> map.put(entry.getkey(), entry.getvalue()));
you have entered common java 8 pitfall: have created stream, described how want process it, didn't triggered processed.
after maptoobj
call should trigger processing via calling method collect
, lets list
, , make foreach
call. or directly use collectors.toconcurrentmap
:
intstream.range(1, list.size()) .filter(i -> (i + 1) % 2 == 0) .maptoobj(i -> new abstractmap.simpleentry<>(list.get(i - 1), list.get(i))) .collect(collectors.toconcurrentmap(o -> o.getkey(), o -> o.getvalue()))
Comments
Post a Comment