2

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?

1 Answer 1

4

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]
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.