java - Sort List using Map, sort it by count -
i sort list(list) value(count), , after key(item). asu arraylist of string;
system.out.println(asu); [3100, 3100, 3100, 1029, 1029, 1029, 1029, 1029, 1029, 1029, 100, 100, 100, 100, 100, 2005, 2005, 2005, 2005, 2005, 2005, 2005, 400, 400, 400, 400, 202, 202, 10] list<string> list = arraylist<>(); map<string, integer> counts = new hashmap<>(); // fill list values.... (string item:list) { integer count = counts.get(item); if (count == null) { // first time have seen item, count should one. count = 1; } else { // increment count one. count = count + 1; } counts.put(item, count); } collections.sort(asu, new comparator<string>() { @override public int compare(string left, string right) { return integer.compare(counts.get(left), counts.get(right)); } }); system.out.println(asu); [10, 202, 202, 3100, 3100, 3100, 400, 400, 400, 400, 100, 100, 100, 100, 100, 1029, 1029, 1029, 1029, 1029, 1029, 1029, 2005, 2005, 2005, 2005, 2005, 2005, 2005,]
the result after should following(return value in list):
system.out.println(asu); [10, 202, 202, 3100, 3100, 3100, 400, 400, 400, 400, 100, 100, 100, 100, 100, 2005, 2005, 2005, 2005, 2005, 2005, 2005, 1029, 1029, 1029, 1029, 1029, 1029, 1029]
and please, not advice "treemap"
just modify comparator use counts first , key itself:
collections.sort(asu, new comparator<string>() { @override public int compare(string left, string right) { int countcompare = counts.get(left).compareto(counts.get(right))); if(countcompare != 0) { return countcompare; } return left.compareto(right); } });
i'm assuming sorting list no null values
Comments
Post a Comment