Home > Back-end >  Get the most common element of an Arraylist
Get the most common element of an Arraylist

Time:12-15

I have an ArrayList from Type Cell. The ArrayList has values from Cells of an Excelsheet. I have tried different solutions from this site, but no one from them could was the right one. Thats why i have no Code to show you what i did. Almost every solution are for String.

I need to get the most common value in my ArrayList.

I tried to replace in the solutions the Strings with cell.getNumericValue() and change the Type of Double but it didnt worked.

Has anybody a solution for my problem?


Map<Cell, Long> f = dataaccx
                .stream()
                .collect(Collectors.groupingBy(v -> v, Collectors.counting()));
        Cell maxOccurence =
                Collections.max(f.entrySet(), Comparator.comparing(Map.Entry::getValue)).getKey();

        System.out.println(maxOccurence.getNumericCellValue());

Thats one Example what i tried. dataaccx is my Arraylist.

CodePudding user response:

You should group by the numeric value of the cell instead of the object itself.

Map<Double, Long> f = cells
        .stream()
        .collect(Collectors.groupingBy(Cell::getNumericCellValue, Collectors.counting()));
Map.Entry maxOccurence =
        Collections.max(f.entrySet(), Comparator.comparing(Map.Entry::getValue));
System.out.println(maxOccurence.getKey());

CodePudding user response:

If multiple most common values are possible and need to be printed, then it might be better to build the frequency map and find the maximal frequency in a single run using plain loop while building the map.

Stream API may be applied then to print the results.

int max = 0;
Map<Double, Integer> freqMap = new LinkedHashMap<>();
for (Cell c : cells) {
    int freq = freqMap.merge(c.getNumericCellValue(), 1, Integer::sum);
    if (freq > max) {
        max = freq;
    }
}
final int maxFreq = max; // max is not final and cannot be used in lambda below
freqMap.entrySet()
    .stream()
    .filter(e -> e.getValue() == maxFreq)
    .map(Map.Entry::getKey)
    .forEach(System.out::println);
  • Related