0

I have the following hash map

Map<String,Double> map_1 = new LinkedHashMap<>();

with some keys: e.g. ["hello_1", "hello_2", "hello_3"].

Then, I iterate through these keys using stream API and saving new results in map2:

 Map<String,Double> map_2 = new LinkedHashMap<>();
 map_2 = map_1.keySet()
                .stream()
                .collect(
                        Collectors.toMap(entry -> entry, 
                                entry -> {
                                     Double value = map_1.get(entry);
                                     return (value + 5);
                                }));

but the new hash map has keys in another order, despite it is defined as LinkedHashMap. I think the problem is during stream + collect steps.

Anyone could suggest me a solution? Thanks

Stefan Zobel
  • 3,182
  • 7
  • 28
  • 38
Fab
  • 1,145
  • 7
  • 20
  • 40
  • There is no sense in initializing `map_2` with a `LinkedHashMap` instance, you are overwriting it with an entirely different object when assigning a new value to the `map_2` variable. By the way, if you want to add `5` to all values of a `Map`, you can simple use `map_1.replaceAll((key,value) -> value+5);` to do it in-place. If you still need a second map, `Map map_2=new LinkedHashMap<>(map_1); map_2.replaceAll((key,value) -> value+5);` can do it. – Holger Apr 03 '17 at 16:32
  • map_1.keySet() .stream() .collect( Collectors.toMap(entry -> entry, entry -> map_1.get(entry) +5, (e1,e2)-> e1, LinkedHashMap::new)); – Manikandan Balasubramanian Jan 11 '18 at 05:32

1 Answers1

0

The order of the keys actually gets messed up in the collect step in this case.

You need to specify that you want to collect to a LinkedHashMap.

john16384
  • 7,800
  • 2
  • 30
  • 44