Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Top N Strings by quantity from input list of strings
import java.util.*;
public class GetTop{
public static void main(String[] args){
List<String> input = new ArrayList<>();
input.add("one");
input.add("two");
input.add("two");
input.add("three");
input.add("three");
input.add("three");
input.add("four");
input.add("four");
input.add("four");
input.add("four");
input.add("5");
input.add("5");
input.add("5");
input.add("5");
input.add("5");
System.out.println(new GetTop().getTopThree(input, 3));
}
public List<String> getTopThree(List<String> input, Integer topAmount){
Map<String, Integer> stringCounts = new HashMap<>();
for(String current: input){
if(stringCounts.get(current)==null){
stringCounts.put(current, 1);
}else{
Integer newValue = stringCounts.get(current);
stringCounts.put(current, ++newValue);
}
}
NavigableMap<Integer, List<String>> result = new TreeMap<>();
for(Map.Entry<String, Integer> entry: stringCounts.entrySet()){
Integer count = entry.getValue();
if(result.get(count)==null){
List<String> resultList = new ArrayList<>();
resultList.add(entry.getKey());
result.put(count, resultList);
}else{
result.get(count).add(entry.getKey());
}
}
List<String> returned = new ArrayList<>();
int j = returned.size();
while(!result.isEmpty() && j < topAmount){
Map.Entry<Integer, List<String>> entry = result.pollLastEntry();
List<String> tempList = entry.getValue();
for (int i = 0; i < tempList.size() && j < topAmount; i++){
returned.add(tempList.get(i));
j = returned.size();
}
}
return returned;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.