0

I have a custom class, PDFDataItem, providing the getValue() method which returns a double value (see the attached code). I also have an ArrayList of several PDFDataItem instances, each one with a specific value: different instances can have the same value. What I would like to do is to create a LinkedHashMap where to store, univocally, the values of the instances and, for each value found, the number of occurencies (i.e. the number of instances in which it compares). Of course, I can find lots of tricks to reach my goal, but I'd like to know if a quick method (possibly using lambda) exists.

public class PDFDataItem{

    double value;

    public PDFDataItem(double value){
        this.value = value;
    }

    public double getValue(){
        return value;
    }
}
Tagir Valeev
  • 97,161
  • 19
  • 222
  • 334
Roberto
  • 243
  • 1
  • 5
  • 15

1 Answers1

15

You can use a Stream<PDFDataItem> with Collectors.groupingBy() Collector to group the PDFDataItem instances by the value property and then count the number of elements in each group using the Collectors.counting() Collector.

Map<Double,Long> valueCounts = 
    pdfList.stream()
           .collect(Collectors.groupingBy(PDFDataItem::getValue,Collectors.counting()));
Eran
  • 387,369
  • 54
  • 702
  • 768