In my code, I've got a few maps. Then I have a method like the one below, which takes one of the maps, sorts the entries by their value and returns a list of the top ones, with the amount given by the parameter.
Example:
if the input map is like
- "a" = 5,
- "b" = 4,
- "c" = 8,
- "d" = 0,
and I call the method with quantity = 2 in the parameter, I'm given a list of the 2 highest map entries, sorted decreasingly
- "c" = 8,
- "a" = 5.
Right now, I have one such method for each of the maps and they only differ in:
- the
<Type1, Type2>
declarations all over the method, and - the
(distances.entrySet());
population of the all list.
Can I generalize this somehow to have just one alike method, being able to receive any of the types?
private static Map<String, Double> distances = new TreeMap<>();
private static Map<String, Integer> titles = new TreeMap<>();
private static Map<Integer, Integer> hours = new TreeMap<>();
private static Map<Date, Integer> days = new TreeMap<>();
public static List<Entry<String, Double>> getTopDistances(int quantity) {
List<Map.Entry<String, Double>> all = new ArrayList<>(distances.entrySet());
List<Map.Entry<String, Double>> requested = new ArrayList<>();
Collections.sort(all, new Comparator<Map.Entry<String, Double>>() {
@Override
public int compare(Entry<String, Double> e1, Entry<String, Double> e2) {
return (e2.getValue().compareTo(e1.getValue()));
}
});
int i = 0;
while (all.iterator().hasNext() && ++i <= quantity) {
requested.add(all.get(i - 1));
}
return requested;
}
I can surely continue with all the methods separated, but I sense a better way of doing it. Have researched generics, wildcards, collections and interfaces, which I think is the way to go, yet I still need a push.