I am trying to sort a List
of objects based on the values in the Map
.
LinkedHashMap<String, Integer> map = new HashMap<>();
map.put("1233", 30);
map.put("1562", 5);
map.put("1243", 10);
map.put("1872", 20);
Based on values in this map I want to sort the following list:
l = [
{ id:1562,name:"xxx" },
{ id:1233,name:"yyy" },
{ id:1243,name:"zzz" },
{ id:1872,name:"xxx" }
]
Expected output:
l = [
{ id:1233,name:"yyy" },
{ id:1872,name:"xxx" },
{ id:1243,name:"zzz" },
{ id:1562,name:"xxx" }
]
I have tried bubble sort with specific condition but it is taking too much time:
int n = l.size();
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (map.get(l.get(j) > map.get(l.get(j+1)) {
swap(j, l);
}
}
}
private void swap(int j, List<L> l) {
l temp = l.get(j);
l.set(j, l.get(j + 1));
l.set(j + 1, temp);
}
Is there any better option, or any other data structure?