Get Enum Values as List of String in Java 8

Get values of enum as list of strings

Add a getter for the value:

public enum DangerShipment {
// Code from the OP omitted for brevity

public String getValue() {
return value;
}
}

And use it when constructing the list:

List<String> dangerlist = Stream.of(DangerousShipment.values())
.map(DangerousShipment::getValue)
.collect(Collectors.toList());

Get from List element matching the ENUM

You can filter and get the first one using .findFirst().

Optional<MyEnum> res = Arrays.stream(MyEnum.values())
.filter(e -> myList.contains(e.getValue()))
.findFirst();

if(res.isPresent()){
MyEnum data = res.get(); // matched enum
}

Convert List<Enum> to List<String> in Java

How about this:

        List<A> list = new ArrayList<>();
list.add(A.VALUE1);
list.add(A.VALUE2);
list.add(null);
List<String> collect = list.stream().map(Optional::ofNullable) //Stream<Optional<..>>
.map(opt -> opt.orElse(null)) //Stream<A>
.map(Objects::toString) //Stream<String>
.collect(Collectors.toList());

How to iterate Enum values using java 8 stream api

Convert enum array to stream

Stream.of(Enum.values()).map....

for your example would be:

List<Integer> list= Stream.of(Board.values()).map(Board::getId).collect(Collectors.toList());

Return enum array for a list of given strings contained in the enum using streams

In your SomeEnum you can build a Map<String, SomeEnum> from string name to enum and initialize it during class loading time. Then declare a public static method in your SomeEnum named fromString which returns an enum constant for a given string if one exists.

private static final Map<String, SomeEnum> stringToEnum = Arrays.stream(values())
.collect(Collectors.toMap(SomeEnum::toString, e -> e));

public static SomeEnum fromString(String name) {
return stringToEnum.get(name);
}

Then use it in your client code. Here's how it looks.

List<SomeEnum> enumList = someStringList.stream()
.map(SomeEnum::fromString)
.collect(Collectors.toList());

Getting the enum names in a list of string in Java

Change the map to Forms::toString

   public static List < String > names() {
return Stream.of(Forms.values())
.map(Forms::toString)
.collect(Collectors.toList());
}

And if you want to use the value (bad name for a variable):

   public static List < String > names() {
return Stream.of(Forms.values())
.map(Forms::getValue)
.collect(Collectors.toList());
}
public String getValue() {
return this.value;
}


Related Topics



Leave a reply



Submit