Sorting the list based on the priority from the card
I have a simple map and need to create a list that sorts based on the number in ascending order from the given list:
Map auto = new HashMap();
auto.put("Merc", 3);
auto.put("Citroen", 5);
auto.put("Opel", 10);
auto.put("BMW", 20);
List<String> given = new ArrayList<>();
given.add("Opel");
given.add("BMW");
given.add("Citroen");
So, this list needs to be sorted so that it is in this order: Citroen, Opel, BMW. I thought:
- create another map, then iterate over the list
- get the number from the first card
- enter number as key and name as value in new card
- sort the card by key.
- iteration threw a new map and then added the values to the list
This seems awful: /, any suggestions and possibly the best data structures to use?
+3
source to share
5 answers
Using Java 8, you can do.
Map<String, Integer> auto = new HashMap<>();
auto.put("Merc", 3);
auto.put("Citroen", 5);
auto.put("Opel", 10);
auto.put("BMW", 20);
List<String> given = new ArrayList<>();
given.add("Opel");
given.add("BMW");
given.add("Citroen");
// to sort the selected elements.
given.sort(Comparator.comparing(auto::get));
// to sort all elements.
List<String> names = auto.entrySet().stream()
.sorted(Comparator.comparing(Map.Entry::getValue))
.map(Map.Entry::getKey)
.collect(Collectors.toList());
Breaking this
List<String> names =
// give the set of entries as a Stream.
auto.entrySet().stream()
// sort these entries, using the field returned by getValue()
.sorted(Comparator.comparing(Map.Entry::getValue))
// now sorted, turn each Entry into just the getKey()
.map(Map.Entry::getKey)
// now we have a stream of keys, turn this into a List<String>
.collect(Collectors.toList());
+3
source to share
Collections.sort(given, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return auto.get(o1).compareTo(auto.get(o2));
}
});
Or with a lambda:
Collections.sort(given, (o1, o2) -> auto.get(o1).compareTo(auto.get(o2)));
A core Java 8 zero security solution based on multiple answers
given.sort(Comparator.comparing((s) -> auto.getOrDefault(s, Integer.MAX_VALUE)));
+4
source to share
Map<String,Integer> auto = new HashMap<String,Integer>();
auto.put("Merc", 3);
auto.put("Citroen", 5);
auto.put("Opel", 10);
auto.put("BMW", 20);
Set<Map.Entry<String,Integer>> set = auto.entrySet();
List<Map.Entry<String,Integer>> list = new ArrayList<Map.Entry<String,Integer>>(set);
Collections.sort(list,new Comparator<Map.Entry<String,Integer>>(){
@Override
public int compare(Entry<String, Integer> o1,
Entry<String, Integer> o2) {
return o1.getValue().compareTo(o2.getValue());
}
});
Once you have the Map.Entry list objects, you can retrieve the key using Entry.getKey()
0
source to share