0

I have this situation and I'm not sure why is this happening, maybe you can help me on this.

I have a class MyClass with this structure. (with getters & setters)

public class MyClass {

private String id;
private String title;
private boolean anyBoolean;

And I added some static attributes such us

public class MyClass {

public static final Group CONS_1 = new Group("cons_1","Cons 1", false);
public static final Group CONS_2 = new Group("cons_2","Cons 2", true);

private String id;
private String title;
private boolean anyBoolean;

public MyClass(String id, String title, boolean anyBoolean) {
        this.id = id;
        this.title = title;
        this.anyBoolean = anyBoolean;
}

Just FYI, I didn't use enums because I have to serialize all the attributes and with the enums it was serializing only the name. Later I realize it will good to have a way to expose these constants by ID such as

public static Map<String, MyClass> myMap;

I tried a basic approach like

static {
        myMap = new HashMap<>();
        myMap.put(CONS_1.getId(), CONS_1);
    }

and it worked, obviously. But I wondered if I could do this with Stream, like

myMap = Stream.of(CONS_1, CONS_2).collect(Collectors.groupingBy(MyClass::getId));

But is not working, because getId() is non static.

So my question is why the second way is not working since both approaches looks equivalent?

Thanks!

apophis
  • 374
  • 3
  • 11
psabbate
  • 767
  • 1
  • 5
  • 22
  • which part @niceman? – psabbate Oct 24 '16 at 18:10
  • why not use [EnumMap](https://docs.oracle.com/javase/8/docs/api/java/util/EnumMap.html) – niceman Oct 24 '16 at 18:16
  • This has nothing to do with `getId` not being `static`. As explained [here](http://stackoverflow.com/a/40174196/2711488), the compiler loves to complain about non-static methods when there are other type errors. In your case, `groupingBy` returns a `Map<…,List<…>>`. – Holger Oct 25 '16 at 10:48

1 Answers1

1

Finally I make it work. The proper way to create that map is

myMap = Stream.of(CONS_1, CONS_2).collect(Collectors.toMap(MyClass::getId, Function.identity()));

I don't understand why the compiler complained about the static method though.

psabbate
  • 767
  • 1
  • 5
  • 22
  • 2
    Note: you can write an 'identity lambda' like `m -> m`, which is shorter than typing out `Function.identity()`, if slightly less clear to the uninitiated. – David Conrad Oct 25 '16 at 07:37
  • 1
    I have always preferred the `m -> m` route to `Function.identity()` as its a lot less verbose. – Ash Oct 25 '16 at 11:17