Skip to content
Advertisement

Sorting based on order mentioned in a static map using java

How to sort a list of strings based on order mentioned in static map having item of list as key.

List={“AU”,”I”,”U”, “O”, “A1”}

Need to sort the above list of string using the below map which has equivalent key and order in which sort has to be done.

static Map<String, Integer> map= new LinkedHashMap<>() ;

static {
 map.put("O",1);
map.put("U",2);
map.put("A1",3);
map.put("I",4);
map.put("AU",5);

} 

How can this be done?

Advertisement

Answer

Using custom comparator which uses this map:

static Map<String, Integer> map = new LinkedHashMap<>();

static {
    map.put("O", 1);
    map.put("U", 2);
    map.put("A1", 3);
    map.put("I", 4);
    map.put("AU", 5);

}

public static void main(String[] args) {
    List<String> list = new ArrayList<>(List.of("AU", "I", "U", "O", "A1"));
    list.sort(Comparator.comparing(a -> map.get(a)));
    System.out.println(list); // [O, U, A1, I, AU]
}
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement