Enum enhancement
Giguere, Thierry
thierry.giguere at bnc.ca
Fri Dec 7 14:13:11 UTC 2018
Hello,
Related to the follow link and JEP 301<https://openjdk.java.net/jeps/301> :
http://mail.openjdk.java.net/pipermail/amber-spec-experts/2018-December/000876.html
What is also missing and long-time due for enum right now and could be added quickly is more methods:
1) We need to be able to iterate efficiently on enum. Currently calling method T[] values() duplicate the internal array. Moreover you need to go through method Arrays.stream() to convert the newly created array to stream. Adding a stream() method and a forEach() method would help fix this problem. Optionally a iterator() method could be provided
Arrays.stream(MyEnum.values()).forEach();
could be replaced by something like :
MyEnum.forEach();
And
Arrays.stream(MyEnum.values()).map(...
could be written :
MyEnum.stream().map(...
2) T valueOfOrDefault : pretty much like getOrDefault of the map interface. This method don't throw exception and fallback on default value. That would ease use of enum in stream / lambda programming
@Nonnull
MyEnum myEnum = MyEnum.DEFAULT_VALUE;
try {
myEnum = MyEnum.valueOf(...);
} catch (NullPointerException | IllegalArgumentException e) {
// Just keep going with on the default value
}
Since exception are thrown it doesn't fit very well in stream / lambda usage. Something like this :
MyData.stream().map(MyEnum::valueOf).forEach()
Must be converted to :
MyData.stream().map(d -> {
try {
return MyEnum.valueOf(...);
} catch (Exception e) {
return MyEnum.DEFAULT_VALUE;
}
}).forEach();
It would be great to write at least something like :
MyData.stream().map(d -> MyEnum.valueOfOrDefault(d, MyEnum.DEFAULT_VALUE)).forEach();
My feeling is these enhancement could be easily and quickly added
Thierry Giguère
CONFIDENTIALITÉ : Ce document est destiné uniquement à la personne ou à l'entité à qui il est adressé. L'information apparaissant dans ce document est de nature légalement privilégiée et confidentielle. Si vous n'êtes pas le destinataire visé ou la personne chargée de le remettre à son destinataire, vous êtes, par la présente, avisé que toute lecture, usage, copie ou communication du contenu de ce document est strictement interdit. De plus, vous êtes prié de communiquer avec l'expéditeur sans délai ou d'écrire à confidentialite at bnc.ca et de détruire ce document immédiatement.
CONFIDENTIALITY: This document is intended solely for the individual or entity to whom it is addressed. The information contained in this document is legally privileged and confidential. If you are not the intended recipient or the person responsible for delivering it to the intended recipient, you are hereby advised that you are strictly prohibited from reading, using, copying or disseminating the contents of this document. Please inform the sender immediately or write to confidentiality at nbc.ca and delete this document immediately.
More information about the amber-dev
mailing list