Reputation: 63
I would like arrange/sort elements in a map based the keys available in a list ( order of elements in a list is immutable) such that keys in map and list should be in same order using java.
Data in a map :
{grocery=150, utility=130, miscellneous=90, rent=1150,
clothes=120, transportation=100}
Data in a list :
[utility, miscellneous, clothes, transportation, rent]
Expected Result :
{utility=130, miscellneous=90, clothes=120, transportation=100, rent=1150 }
Upvotes: 2
Views: 96
Reputation: 131546
That is not a sort.
You want to process the elements by starting from the list.
Supposing that the textual values be String and that the numeric values be Integer, you could do that :
Map<String, Integer> finalMap =
list.stream()
.collect(toMap(o->o, map.get(o), (a,b)->a, LinkedHashMap::new));
or still :
LinkedHashMap<String, Integer> finalMap = new LinkedHashMap<>();
list.forEach(o-> finalMap.put(o, map.get(o));
Upvotes: 3
Reputation: 18255
You have to iterate over the required list of keys and retrieve the values from the Map
. To keep order, you should use LinkedHashMap
:
public static Map<String, Integer> sort(Map<String, Integer> map, String[] keys) {
return Arrays.stream(keys).collect(Collectors.toMap(key -> key, map::get, Integer::sum, LinkedHashMap::new));
}
Upvotes: 0
Reputation: 16908
You can sort the map based on the index of occurrence of the key of the map in the given list by using a Comparator
then to preserve the sort order collect it to a LinkedHashMap
:
public static void main(String[] args) throws Exception {
Map<String, Integer> map = new HashMap<>();
map.put("grocery", 150);
map.put("utility", 130);
map.put("miscellneous", 90);
map.put("rent", 1150);
map.put("clothes", 120);
map.put("transportation", 100);
List<String> list = new ArrayList<>(
Arrays.asList("utility", "miscellneous", "clothes",
"transportation", "rent"));
Map<String, Integer> sortedMap
= map.keySet()
.stream()
.filter(list::contains)
.sorted(Comparator.comparing(list::indexOf))
.collect(LinkedHashMap::new,
(linkMap, key) -> linkMap.put(key, map.get(key)),
Map::putAll);
System.out.println(sortedMap);
}
Output:
{utility=130, miscellneous=90, clothes=120, transportation=100, rent=1150}
Upvotes: 0