Reputation: 2455
I merely want to retrieve the last n values from a tree map without considering any keys or values from the map. But i really don't have any clue on how to do this. Below is a sample piece of code which can pull out first 5 records from the map. How can i modify it to retrieve last n records from the map?
Map startValues = new ArrayList<Map.Entry<String, Integer>>(5);
iterator = sortedMap.entrySet().iterator();
for (int i1 = 0; iterator.hasNext() && i1 < 5; i1++) {
startValues.add(iterator.next());
}
Upvotes: 3
Views: 2557
Reputation: 391
Get map.keySet() and convert it into ArrayList, then you can get last n values using loop as in example below:
Map<Integer, String> map = new HashMap<>();
map.put(1, "Praveen");
map.put(2, "shristi");
map.put(3, "tarang");
Set<Integer> keys = map.keySet();
ArrayList<Integer> list = new ArrayList<>(keys);
for(int i=1;i<list.size();i++) {
System.out.println(map.get(list.get(i)));
}
Upvotes: 0
Reputation: 18041
If sortedMap
variable contains an instance of a TreeMap
then use descendingKeySet()
. It returns a reverse order of the keys contained in there.
Map startValues = new ArrayList<Map.Entry<String, Integer>>(5);
iterator = sortedMap.descendingKeySet().iterator();
for (int i1 = 0; iterator.hasNext() && i1 < 5; i1++) {
startValues.add(sortedMap.get(iterator.next()));
}
Note that in contrast to original code this iterates over keys, not entries. I have not test-compiled it so there might be minor issues with generics and type casting but hopefully the main idea is clear enough.
Upvotes: 4
Reputation: 10789
Ordering in TreeMap
maintained by Comparator
object at the creation time. If Comparator
not provided - it is natural ordering.
The most straightforward solution to create Comparator
that implements reverse sorting, pass this comparator to new TreeMap
, and add all elements from old treemap to new one. That way you can reuse you code sample for retrieving last 5 records.
Upvotes: 1