user1726569
user1726569

Reputation:

How to sort ArrayList of strings with priority that obtained from a HashMap?

I have an ArrayList of ArrayLists and inside those ArrayLists I store Strings, and I would like to sort those string according to their priority that I store on a HashMap. Is there a efficient way to accomplish this task simply iterating over them?

Upvotes: 1

Views: 201

Answers (3)

Sukreet Roy Choudhury
Sukreet Roy Choudhury

Reputation: 180

List<String> arraylist = new ArrayList<>();
    arraylist.add("a");
    arraylist.add("a");
    arraylist.add("a");
    arraylist.add("b");
    arraylist.add("c");
    arraylist.add("c");
    arraylist.add("c");
    arraylist.add("c");
    arraylist.add("d");
    arraylist.add("d");

    Map<String,Integer> hashMap = new HashMap<>();
    hashMap.put("a",3);
    hashMap.put("b",1);
    hashMap.put("c",4);
    hashMap.put("d",2);

    Collections.sort(arraylist, (o1, o2) -> {
        int i = hashMap.get(o1) < hashMap.get(o2) ? 1 : -1;
        return i;
    });

this gives the following output: [c, c, c, c, a, a, a, d, d, b]

Upvotes: 0

Schidu Luca
Schidu Luca

Reputation: 3947

Given that you have a HashMap with priorities you could do this:

List<List<String>> listList = new ArrayList<>();

List<String> listOne = Arrays.asList("A", "B", "C", "D");
List<String> listTwo = Arrays.asList("D", "D", "D", "B");

listList.add(listOne);
listList.add(listTwo);

Map<String, Integer> map = new HashMap<>();
    map.put("A", 1);
    map.put("B", 2);
    map.put("C", 1);
    map.put("D", 4);


listList.forEach(list -> list.sort(Comparator.comparingInt(map::get)));

Note that for this to work, you have to have all the strings from list in your Map with priorities, otherwise you will get a NullPointerException.

Upvotes: 1

lwi
lwi

Reputation: 1712

If I understand you problem correctly, this should do the trick. If you consider this efficient is depending on the performance bounds you have to meet.

    HashMap<String, Integer> priorities = new HashMap<String, Integer>();
    priorities.put("A", 1);
    priorities.put("B", 2);
    priorities.put("C", 3);

    List<List<String>> list = new ArrayList<List<String>>();

    list.add(Arrays.asList("A", "C", "B"));
    list.add(Arrays.asList("B", "A", "B"));
    list.add(Arrays.asList("A", "B", "C"));

    list.forEach(x -> x.sort((string1, string2) -> {
        return priorities.get(string1) - priorities.get(string2);
    }));

    System.out.println(list);

Upvotes: 0

Related Questions