0

I have this code:

Map<List<Object>, Long> collector = root.getReports().stream().collect(
    Collectors.groupingBy(r -> Arrays.asList(i.X(), i.Y(), i.Z(), i.A()), Collectors.counting()));

for(Entry<Object, Long> entry : collector.entrySet())
    System.out.println(String.format("%s = %s", entry.getKey(), entry.getValue()));

Which basically produces this:

[16292, 141, 6, 100] = 2
[16288, 250, 59, 500] = 14
[16286, 250, 91, 50] = 4
[16287, 250, 91, 60] = 29
[16286, 250, 91, 80] = 10
[16293, 141, 6, 100] = 3
[16282, 079, 116, 50] = 9
...

I need to to put this results into a custom class, this one:

@EqualsAndHashCode @ToString
public class CustomReport implements Serializable {
    private static final long serialVersionUID = 2074900904056768029L;

    @Getter @Setter
    private Integer x, y, z;
    
    @Getter @Setter
    private String a;

    @Getter @Setter
    private Long result;
}

There's a way to do this without go through all the list and doing it manually?

c0nf1ck
  • 359
  • 3
  • 14
  • 2
    What do you mean by "manually"? You have to write the code mapping one `Entry, Integer>` to `CustomReport`. – Turing85 Sep 04 '20 at 19:33
  • 1
    Depends what you mean by "go through all the list and doing it manually." You will need to loop over the `entrySet` returned by the collector somehow, whether in a stream or in a for loop, and you will need to manually assign each variable. – Louis Wasserman Sep 04 '20 at 19:33

1 Answers1

1

Not sure if this is what you want. But you can get a Map<CustomReport, Long> directly instead of first creating a Map<List<Object>, Long> and then going through it to convert those objects to your target class.

The prerequisite is that CustomReport should have equals() [1] and hashCode() [2] implemented

Then you can do this:

root.getReports().stream().collect(
    Collectors.groupingBy(i -> new CustomReport(i.X(), i.Y(), i.Z(), i.A()), 
        HashMap::new,
        Collectors.counting()));

I am assuming CustomReport has a compatible constructor too. If you have to initialize with setters, then you can replace the first argument of the classifier with :

i -> {
    CustomReport c = new CustomReport();
    c.setX(i.X());
    ...
    return c;
}
jrook
  • 3,459
  • 1
  • 16
  • 33