-1

Hello I have a hashmap like following :-

HashMap<String, String> map = new HashMap();

map.put("1","a");
map.put("2","b");
map.put("3","c");
map.put("4","d");
map.put("5","e");

I Have a list as following :-

ArrayList<String> list = new ArrayList();
list.add("5");
list.add("1");
list.add("3");
list.add("4");
list.add("2");

I Want the following output map :-

5 -> e
1 -> a
3 -> c
4 -> d
2 -> a
Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
Hasnain Ali Bohra
  • 2,130
  • 2
  • 11
  • 25
  • 7
    "Order `HashMap` according to" is already a lost cause: `HashMap` is inherently unordered. You can use a `LinkedHashMap` to preserve the insertion order. A `SortedMap` can take a `Comparator` to define a predetermined ordering, but I'm not gleaning any such order from your example. – Rogue Jul 26 '22 at 19:24
  • 1
    You can iterate the list and retrieve the map's elements in that order. But you can't order a HashMap. – Olaf Kock Jul 26 '22 at 19:28

5 Answers5

1

If you only want to iterate the entries of the map in the order defined in list, then you could simply do the following:

for (String key : list) {
    if (map.containsKey(key)) {
        System.out.println(map.get(key));
    }
}

Of course, this discards any element within map which is not present in list.

Rogue
  • 11,105
  • 5
  • 45
  • 71
MC Emperor
  • 22,334
  • 15
  • 80
  • 130
  • I think this is one of the better answers in terms of approach (taking advantage of the ~`O(1)` lookup for hashmap), but personally I would use a direct `Map#get` (no `#contains` check) if the map shouldn't contain null values. – Rogue Jul 27 '22 at 12:07
  • @Rogue Yeah, I was playing safe because of the `null`s. But indeed, I think `null` values should not be present in a `Map`, and then I would do the same as you suggested. – MC Emperor Jul 27 '22 at 15:26
1

The easiest is probably the following.

Create a LinkedHashMap filled with the elements of the list and their mapping.

var newMap = list.stream()
  .collect(toMap(x -> x, map::get, (k, v) -> v, LinkedHashMap::new));
Olivier Grégoire
  • 33,839
  • 23
  • 96
  • 137
1

You need to use the LinkedHashMap, it maintains the order.

import java.util.*;
public class sortmapKey {
   public static void main(String args[])
    {
        // This map stores unsorted values
        Map<String, String> map = new HashMap<>();
        // putting values in the Map
        map.put("1","a");
        map.put("2","b");
        map.put("3","c");
        map.put("4","d");
        map.put("5","e");

        //creating array
        ArrayList<String> list = new ArrayList();
        list.add("5");
        list.add("1");
        list.add("3");
        list.add("4");
        list.add("2");
        
        //load values in a LinkedHashMap
        Map<String, String> lmap = new LinkedHashMap<>();
        
        for(String val: list){
            lmap.put(val, map.get(val));
        }
        System.out.println(lmap);
    }
}

output will be, {5=e, 1=a, 3=c, 4=d, 2=b}

5 -> e
1 -> a
3 -> c
4 -> d
2 -> a
Jyoti Prakash
  • 3,921
  • 3
  • 21
  • 24
0

HashMap is not ordered, but you can sort the entries of the Map based on their index in the List and collect it to a LinkedHashMap.

Map<String, String> res = map.entrySet().stream()
           .sorted(Comparator.comparingInt(e -> list.indexOf(e.getKey())))
           .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, 
                                              (a, b) -> b, LinkedHashMap::new));
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
0

The LinkedHashMap class has already been mentioned a few times, however, this class is designed to maintain insertion order. But one can also use TreeMap, which is designed to keep an arbitrary ordering by some Comparator (or the natural ordering if the no-args constructor is used).

I have written some helper method to convert a given list to a Comparator which uses the order provided by the list:

public static <T> Comparator<T> ofOrder(List<T> elements) {
    Map<T, Integer> comparatorMap = IntStream.range(0, elements.size())
        .collect(HashMap::new, (map, value) -> map.put(elements.get(value), value), HashMap::putAll);
    return (T left, T right) -> {
        int leftVal = comparatorMap.getOrDefault(left, Integer.MAX_VALUE);
        int rightVal = comparatorMap.getOrDefault(right, Integer.MAX_VALUE);
        return Integer.compare(leftVal, rightVal);
    };
}

With this method it's fairly easy to get a TreeMap with the desired ordering:

TreeMap<String, String> treeMap = new TreeMap<>(ofOrder(list));
treeMap.putAll(map);
MC Emperor
  • 22,334
  • 15
  • 80
  • 130