简体   繁体   中英

Collect values from an enum with stream doesn't work

I want to have a list with almost all the values from an enum. I tried to do that with the help of stream but I don't know why it is not working.

For example I am trying to do like this:

 SortingType.stream() //
            .filter(d -> !d.getName().equals(SortingType.UNKNOWN.getName()))
            .forEach(u -> {
                sortingList.add(createSortingBE(locale, u, u.name().equalsIgnoreCase(sortingType.name())));
            }); 

.stream() appears with red and I receive this message: " Cannot resolve method 'stream' in 'SortingType' "

Sorting Type

public enum SortingType {
    DISTANCE("DISTANCE", 101, "Sorting POIs by distance"),
    PRICE("PRICE", 104, "Sorting POIS by price"),
    UNKNOWN("UNKNOWN", 000, "Unknown sorting option");

    private String name;
    private Integer identifier;
    private String description;

    SortingType(final String name, final Integer identifier, final String description) {
        this.name = name;
        this.identifier = identifier;
        this.description = description;
    }

    public static SortingType getByName(final String name) {
        return Stream.of(values()).filter(u -> u.name.equalsIgnoreCase(name)).findFirst().orElse(SortingType.UNKNOWN);
    }

    public static SortingType getByIdentifier(final Integer identifier) {
        return Stream.of(values()).filter(u -> u.identifier.equals(identifier)).findFirst().orElse(SortingType.UNKNOWN);
    }

    public String getDescription() {
        return description;
    }

    public Integer getIdentifier() {
        return identifier;
    }

    public String getName() {
        return name;
    }

You should simply add the stream() method like this.

public enum SortingType {

    // .....

    public static Stream<SortingType> stream() {
        return Stream.of(values());
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM