My Arraylist looks like [A, B, D, E, C, A, A, B]
and i want to print to console
A,3
B,2
C,1
D,1
E,1
i.e. based on decreasing frequency and if same frequency, print them lexicographically.
How can I do this in Java?
CodePudding user response:
If the contents of your array are of type char this can be a approached using another array
char[] foo = new char['Z' - 'A'];
then you will loop through your original array incrementing the position of that char in foo. if you use a fast sorting algorithm afterwards afterwards you can just print them out but if i 1 = i then compare them by char value
CodePudding user response:
Create a hashmap, in which there will be one entry per symbol. The symbol itself will be the 'key' and the # of times that symbol shows up will be the value within the hashmap.
Iterate through your list, each time you find a new symbol, add a matching entry to the map, and each time you find an existing symbol, add one to its value in the hashmap
Add the hashmaps' entryset to a list, sort that list using a comparator then print this sorted list out.
public static void main(String[] args) {
String mySymbols = "A,B,D,E,C,A,A,B";
ArrayList<String> myList = new ArrayList<String>();
Collections.addAll(myList, mySymbols.split(","));
HashMap<String, Integer> countingMap = new HashMap<String, Integer>();
for (String s : myList){
if(countingMap.containsKey(s)){
Integer newValue = countingMap.get(s) 1;
countingMap.put(s, newValue);
}
else{
countingMap.put(s, 1);
}
}
List<Entry> entries = new ArrayList<Entry>();
entries.addAll(countingMap.entrySet());
entries.sort(new Comparator<Entry>() {
@Override
public int compare(Entry o1, Entry o2) {
return (Integer)o2.getValue() - (Integer)o1.getValue();
}
});
Iterator iter = entries.iterator();
while(iter.hasNext()){
Entry thisEntry = (Entry) iter.next();
Object key = thisEntry.getKey();
Object value = thisEntry.getValue();
System.out.println(key ", " value);
}
}
CodePudding user response:
You could accomplish this with a Stream.
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;
class MyClass {
public static void main(String...args) {
printListElementFrequencies(Arrays.asList("A", "B", "D", "E", "C", "A", "A", "B"));
}
static void printListElementFrequencies(List<String> list) {
Map<String, Long> frequencies = list.stream().collect(Collectors.groupingBy(s -> s, TreeMap::new, Collectors.counting()));
Comparator<String> sortByFrequencyThenLexicographically = Comparator.<String, Long>comparing(frequencies::get).reversed().thenComparing(Comparator.comparing(s -> s));
list.stream().sorted(sortByFrequencyThenLexicographically).forEach(s -> System.out.println(s ", " frequencies.get(s)));
}
}
Edit: I missed the sorting part.