I have 2 pieces of codes, one written with the java old style and the other is written with lambda expression,
The first:
Class enumClass = getConstantsEnum();
Object[] enumConstants = enumClass.getEnumConstants();
for(Object o:enumConstants) {
try {
constantsMap.put(o.toString(),o.getClass().getDeclaredField("lookupValue").getInt(o));
} catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException
| SecurityException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
Is working fine and filling the map correctly
The other:
Class enumClass = getConstantsEnum();
Object[] enumConstants = enumClass.getEnumConstants();
constantsMap.putAll(Arrays.asList(enumConstants)
.stream().collect(Collectors.toMap
(e -> e.toString(), e -> {
try {
return e.getClass().getDeclaredField("lookupValue").getInt(e);
} catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException
| SecurityException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}finally {
return null;
}
}
)));
Is giving null pointer exception, though by debugging the line e.getClass().getDeclaredField("lookupValue").getInt(e)
I see it gets filled by value
My questions are: 1-what is wrong with this code?
2- how can I debug effectively inside stream methods in eclipse, is there a way to see elements getting populated inside the map one by one as in normal loop ? I could see the first element by putting a breakpoint but then the exceptions is fired immediately
3- is there a cleaner way to handle the exception inside the lambda expression, I tried wrapping the whole code with try/catch but compiler is still complaining that the exception is not handled.
Answer to any question is appreciated :)
EDIT:
Q1 answered by Holger in comments
IDE added