I'm trying, and failing, to retrieve all Enum values and place them in a list using Java 8 and streams. So far I've tried the two approaches below, but neither one returns the value.
What am I doing wrong?
Code:
public class Main {
public static void main(String[] args) {
List<String> fruits1 = Stream.of(FruitsEnum.values())
.map(FruitsEnum::name)
.collect(Collectors.toList());
List<String> fruits2 = Stream.of(FruitsEnum.values().toString())
.collect(Collectors.toList());
// attempt 1
System.out.println(fruits1);
// attempt 2
System.out.println(fruits2);
}
enum FruitsEnum {
APPLE("APPL"),
BANANA("BNN");
private String fruit;
FruitsEnum(String fruit) {this.fruit = fruit;}
String getValue() { return fruit; }
}
}
Output:
[APPLE, BANANA]
[[LMain$FruitsEnum;@41629346]
Desired:
["AAPL", "BNN"]
In Java 10 and later, you can conveniently create a non-modifiable List by passing the EnumSet . The order of the new list will be in the iterator order of the EnumSet . The iterator order of an EnumSet is the order in which the element objects of the enum were defined on that enum. Great insight in this answer!
Enum Class MethodsReturns true one or more bit fields are set in the current instance. Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object. Returns the string representation of the value of this instance.
An EnumSet is a specialized Set collection to work with enum classes. It implements the Set interface and extends from AbstractSet: Even though AbstractSet and AbstractCollection provide implementations for almost all the methods of the Set and Collection interfaces, EnumSet overrides most of them.
In Haskell, they are represented by the type classes Bounded (for types with minimum and maximum bounds) and Enum (for types whose values can be enumerated by the Int values). The Bounded type class defines only two methods: class Bounded a where minBound :: a maxBound :: a {-# MINIMAL minBound, maxBound #-}
You need to map
with getValue
List<String> fruits = Stream.of(FruitsEnum.values())
.map(FruitsEnum::getValue) // map using 'getValue'
.collect(Collectors.toList());
System.out.println(fruits);
this will give you the output
[APPL, BNN]
This should do the trick:
Arrays.stream(FruitsEnum.values())
.map(FruitsEnum::getValue)
.collect(Collectors.toList());
Using of EnumSet
is other way:
List<String> fruits = EnumSet.allOf(FruitsEnum.class)
.stream()
.map(FruitsEnum::getValue)
.collect(Collectors.toList());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With