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
  • 92,683
  • 18
  • 210
  • 320
Roberto
  • 223
  • 1
  • 4
  • 15

1 Answers1

14

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
  • 374,785
  • 51
  • 663
  • 734