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!