Reputation: 93
Hi I have a MAP which gives all records after counting elements. In this record set last element of MAP is the final output of counted records for me .. but how to fetch it and assign it to String ( to use it for later purpose)?
Map<String, Integer> stringsWithCount = new TreeMap<String,Integer>();
for (Message msg : convInfo.messages) {
// where ever your input comes from: turn it into lower case,
// so that "ccc" and "CCC" go for the same counter
String item = msg.userName;
if (stringsWithCount.containsKey(item)) {
stringsWithCount.put(item, stringsWithCount.get(item) + 1);
} else {
stringsWithCount.put(item, 1);
}
}
I am travesing the map like below
for (Entry<String, Integer> entry : stringsWithCount.entrySet()) {
System.out.println(entry.getKey()+"("+entry.getValue()+")");
}
Now its printing
G_LO(1)
FCHAN95(1)
G_LO(1)
FCHAN95(2)
G_LO(1)
FCHAN95(2)
G_LO(1)
WVU(1)
FCHAN95(2)
G_LO(1)
SWONG00(1)
WVU(1)
FCHAN95(3)
G_LO(1)
SWONG00(1)
WVU(1)
FCHAN95(4)
G_LO(1)
SWONG00(1)
WVU(1)
FCHAN95(5)
G_LO(1)
SWONG00(1)
WVU(1)
FCHAN95(6)
G_LO(1)
SWONG00(1)
WVU(1)
here starting from last unique records I want to access --> FCHAN95(6) G_LO(1) SWONG00(1) WVU(1)
Upvotes: 0
Views: 1113
Reputation: 3507
As treemap has built in method like below
String lastKey=((TreeMap<String, Integer>) stringsWithCount).lastKey(); // for last key
Integer lastRecord =((TreeMap<String, Integer>) stringsWithCount).get(lastKey) // for last record
//stringsWithCount is your map variable
Upvotes: 2