3

I am working with Java 8 Streams I have a class like below:

public class ShareDao {
    private String senderId;
    private String receiverId;

    public String getSenderId() {
        return senderId;
    }

    public String sharingMode(){
        return this.receiverId != null && !this.receiverId.trim().isEmpty() ? "incoming" : "outgoing";
    }
}

Now what I am trying to do is, I want to:

  1. Filter out the records where senderId is invalid (using a Map<> lookup)
  2. Group the collection by the senderId and then further group them by the shareMode.

Below is my code:

Map<String, Map<String, List<ShareDao>>> p = records.stream()
            .filter(shared -> userMap.containsKey(shared.getSenderId()))
            .collect(Collectors.groupingBy(ShareDao::getSenderId), Collectors.groupingBy(ShareDao::sharingMode, Function.identity()));

It throws me the error:

Error:(105, 90) java: no suitable method found for groupingBy(Share[...]gMode,java.util.function.Function) method java.util.stream.Collectors.groupingBy(java.util.function.Function) is not applicable (cannot infer type-variable(s) T,K (actual and formal argument lists differ in length)) method java.util.stream.Collectors.groupingBy(java.util.function.Function,java.util.stream.Collector) is not applicable (no instance(s) of type variable(s) T exist so that java.util.function.Function conforms to java.util.stream.Collector) method java.util.stream.Collectors.groupingBy(java.util.function.Function,java.util.function.Supplier,java.util.stream.Collector) is not applicable (cannot infer type-variable(s) T,K,D,A,M (actual and formal argument lists differ in length))

While Intellij Idea raises the error

Non-Static method cannot be referenced from static context

iam.Carrot
  • 4,976
  • 2
  • 24
  • 71
  • Possible duplicate of [What is the reason behind "non-static method cannot be referenced from a static context"?](https://stackoverflow.com/questions/290884/what-is-the-reason-behind-non-static-method-cannot-be-referenced-from-a-static) – CodeMatrix Feb 23 '19 at 11:47
  • 3
    Can you please read the question again? How is it a duplicate? – iam.Carrot Feb 23 '19 at 12:06

1 Answers1

2

Based on what you're trying to achieve

  • Filter out the records where senderId is invalid (using a Map<>
    lookup)
  • Group the collection by the senderId and then further group them by the shareMode.

you can instead use:

Map<String, Map<String, List<ShareDao>>> p = records.stream()
        .filter(shared -> userMap.containsKey(shared.getSenderId())) // filter records
        .collect(Collectors.groupingBy(ShareDao::getSenderId, // grouping by senderId
                Collectors.groupingBy(ShareDao::sharingMode)));  //further grouping by sharingMode

Note:

  1. groupingBy attributes results in values to be aggregated as a List.

  2. the Collector defined within the collect as it differs from your attempt.

Naman
  • 27,789
  • 26
  • 218
  • 353