java - Sorting the values in the treemap -
i read text file , stored in tree map each key having multiple values.like,
key: a1bg values: g5730 a4527 e3732 b0166
key: bca3 values: c1478 a4172 d8974 b1432 e2147
key: db8c values: n0124 k7414 x9851
since tree map got keys sorted.now,i want sort values corresponding key.and o/p as,
key: a1bg values: a4527 b0166 e3732 g5730
key: bca3 values: a4172 b1432 c1478 d8974 e2147
key: db8c values: k7414 n0124 x9851
iam new java.can on this. here code
bufferedreader reader = new bufferedreader(new filereader("e:\\book\\datasone.txt")); map<string, string> map = new treemap<string,string>(); string currentline; while ((currentline = reader.readline()) != null) { string[] pair = currentline.split("\\s+"); key = pair[0]; value = pair[1]; if(map.containskey(key)) { value += map.get(key); } else { map.put(key,value); } } (string name: map.keyset()) { string key =name.tostring(); string value = map.get(name).tostring(); system.out.println(key + " " + value+ " "); }
if there no duplicate values store values treeset
public class testmap { public static void main(string[] args) { list<string> lines = new arraylist(); lines.add("a1bg g5730"); lines.add("a1bg a4527"); lines.add("a1bg e3732"); lines.add("a1bg b0166"); lines.add("bca3 c1478"); lines.add("bca3 a4172"); lines.add("bca3 d8974"); lines.add("bca3 b1432"); lines.add("bca3 e2147"); lines.add("db8c n0124"); lines.add("db8c k7414"); lines.add("db8c x9851"); map<string, set<string>> map = new treemap<string,set<string>>(); for(string currentline : lines){ string[] pair = currentline.split("\\s+"); string key = pair[0]; string value = pair[1]; if(!map.containskey(key)){ set<string> set = new treeset<string>(); map.put(key,set); } map.get(key).add(value); } (string name: map.keyset()) { string key =name.tostring(); system.out.print(key); (string value : map.get(name)){ system.out.print(" " + value); } system.out.println(); } } }
output
a1bg a4527 b0166 e3732 g5730 bca3 a4172 b1432 c1478 d8974 e2147 db8c k7414 n0124 x9851
Comments
Post a Comment