You're better off just creating a class for a name and number of occurrences.
import java.util.Objects;
public class NameCount implements Comparable<NameCount> {
private final String name;
private int count;
public NameCount(String name) {
this.name = name;
count = 0;
}
public NameCount(String name, int count) {
this.name = name;
this.count = count;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public void incrementCount() {
count++;
}
@Override
public int hashCode() {
return Objects.hashCode(this.name);
}
@Override
public boolean equals(Object obj) {
if(obj == null) return false;
if(getClass() != obj.getClass()) return false;
final NameCount other = (NameCount)obj;
if(!Objects.equals(this.name, other.name)) return false;
return true;
}
@Override
public int compareTo(NameCount o) {
return o.count - count;
}
}
You can then define your map as Map<Integer, List<NameCount>>
. Note how the above class defines equality and hash code based only on the name, so if you want to see if a name is in a list, you can just create a NameCount
for it and use contains
. The compareTo
implementation orders from higher count to lower, so when getting the List<NameCount>
for a given year, you can then use Collections.sort(list)
on it and ask for the index for a NameCount
with the same name.
public void test(Map<Integer, List<NameCount>> map) {
int year = 2017;
List<NameCount> list = map.get(year);
// Do null-check on list first when using this...
Collections.sort(list);
NameCount check = new NameCount("Abigail");
int rank = list.indexOf(check) + 1;
}
It might seem to make more sense to use TreeSet
map values to guarantee unique name entries and keep them sorted all the time, but note that TreeSet defines equality based on comparison, not equals, and it wouldn't let you get the index.