-1

I want to group a map object by key. I try with this code but i have a compile error:

Non-static method cannot be referenced from a static context

My code:

Map<String, List<A>> getAMap() {        
    return Arrays.stream(SomeArray.values())
            .map(map -> createObject())
            .collect(Collectors.groupingBy(Map.Entry::getKey, 
                  Collectors.mapping(Map.Entry::getValue, Collectors.toList())));
}


private Map<String, A> createObject() 
    final A a = new A(some attributes);
    Map<String, A> map = new LinkedHashMap<>();
    map.put(some key, a);
    .... // add another values. 
    return map;
}

I need something like

{
"a", {a1, a2, a3},
"b", {a4, a5, a6},
}
emoleumassi
  • 4,881
  • 13
  • 67
  • 93
  • `SomeArray.values()`? may be `SomeEnum`? – Eugene Aug 20 '18 at 14:00
  • 1
    Can you show where you call `getAMap()`. The error message indicates that you call it from a static method (maybe `main`?) without an object reference. Check this: [calling non-static method in static method in Java](https://stackoverflow.com/questions/2042813/calling-non-static-method-in-static-method-in-java). – Malte Hartwig Aug 20 '18 at 14:02
  • 3
    `createObject()` returns a `Map`, you are trying to use methods belonging to `Map.Entry`. Regarding the error message, consider the first paragraph of [this answer](https://stackoverflow.com/a/40174196/2711488)… – Holger Aug 20 '18 at 14:04

1 Answers1

6

It looks like your code is wrong on some levels and that error message is not what exactly happens.

For example createObject() returns a Map so you get a Stream<Map<...>>, so obviously .collect(Collectors.groupingBy(Map.Entry::getKey... will not work. You need to change your code a bit for this to work:

Arrays.stream(someArray)
            .flatMap(map -> createObject().entrySet().stream())
            .collect(Collectors.groupingBy(Entry::getKey,
                    Collectors.mapping(Entry::getValue, Collectors.toList())));
Eugene
  • 117,005
  • 15
  • 201
  • 306