This can be implemented in different ways:
- Convert
keySet of the sorted map into list and use indexes to build a map using Collectors.toMap:
List<Integer> keys = new ArrayList<>(map.keySet());
Map<Integer, Integer> res = IntStream
.range(0, list.size())
.boxed()
.collect(Collectors.toMap(i -> keys.get(i), i -> list.get(i), (a, b)-> a, TreeMap::new));
System.out.println(res);
- Use
AtomicInteger and its getAndIncrement when streaming by keys of the sorted map to refer the element in the list with the updates:
AtomicInteger i = new AtomicInteger(0);
Map<Integer, Integer> res2 = map.keySet()
.stream()
.collect(Collectors.toMap(
k -> k,
k -> list.get(i.getAndIncrement()),
(a, b) -> a,
TreeMap::new // or LinkedHashMap::new as keys are sorted
));
System.out.println(res2);
- Similarly to previous implementation, current map may be modified using
forEach of the map's entrySet():
AtomicInteger j = new AtomicInteger(0);
map.entrySet().forEach(e -> e.setValue(list.get(j.getAndIncrement())));
Extra safety measures may need to be added, for instance, handling of the case when the map and the list are of different size.
These examples prove the feasibility of such task, though the task itself does not seem to be an appropriate application of Stream API.