Skip to content

Instantly share code, notes, and snippets.

@danielsimao
Created May 20, 2020 22:33
Show Gist options
  • Save danielsimao/bc7407cceab107e00db5d376812e48f2 to your computer and use it in GitHub Desktop.
Save danielsimao/bc7407cceab107e00db5d376812e48f2 to your computer and use it in GitHub Desktop.
sorted
HashMap<String, Integer> origens = new HashMap<>();
for(Flight f: listOfFlights) {
if(!origens.containsKey(f.getOrigin())) {
origens.put(f.getOrigin(), 1);
} else {
Integer currentCount = origens.get(f.getOrigin());
origens.replace(f.getOrigin(), currentCount + 1);
}
}
Comparator<String> comparator = new ValueComparator(origens);
//TreeMap is a map sorted by its keys.
//The comparator is used to sort the TreeMap by keys.
TreeMap<String, Integer> result = new TreeMap<String, Integer>(comparator);
result.putAll(origens);
System.out.printf(String.format("%-20s %-2s" , "Origem", "Voos\n"));
for(Map.Entry<String, Integer> f: result.entrySet()) {
System.out.printf(String.format("%-20s %-2s" , f.getKey(), f.getValue() + "\n"));
}
static class ValueComparator implements Comparator<String>{
HashMap<String, Integer> map = new HashMap<String, Integer>();
public ValueComparator(HashMap<String, Integer> map){
this.map.putAll(map);
}
@Override
public int compare(String s1, String s2) {
if(map.get(s1) >= map.get(s2)){
return -1;
}else{
return 1;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment