I have a list of input strings of the form "code-marks"
For example,
1001-40
1002-54
1003-23
1001-45
1004-60
Expected output:
1004-60
1002-54
1001-45
1003-23
If the values are repeated (like 1001) the latest is used and also need to be sorted.
My first bet was to use TreeMap but it would pose a problem of sorting based on values which is impossible.
Scanner in = new Scanner(System.in);
SortedMap<Integer, Integer> map = new TreeMap<Integer, Integer>(new Comparator<Integer>() {
public int compare(Integer i, Integer j) {
return(j.compareTo(i));
}
});
int i=0;
while(i<5)
{
String[] s = in.next().split("\\-");
map.put(Integer.parseInt(s[0]),Integer.parseInt(s[1]));
i++;
}
// Get a set of the entries
Set set = map.entrySet();
// Get an iterator
Iterator itr = set.iterator();
// Display elements
while(itr.hasNext()) {
Map.Entry me = (Map.Entry)itr.next();
System.out.print(me.getKey() + ": ");
System.out.println(me.getValue());
}
What is the best approach to this situation?