How can I exclude an enum named CodesType in this code ?
Code returns a list of objects of the EventsData class and I want to be able to skip one designated enum.
I would like to exclude an Enum named CodesType. By default it is added in the mapEvents variable which means that I would have to add some filtering there so that the Enum named CodesType is skipped. I just don't know how to implement correctly. I tried something like this, but it doesn't work .filter(type -> type != CodesType)
.
You can also see in the code that I manually add two EventsData objects such as CodesType and SupportType. Therefore, I want to exclude this CodesType object that is added at the beginning so that a duplicate is not created. (It has to exist because the objects I add manually are created based on it, but it doesn't have to be retrieved so I want to exclude it).
private List < EventsData > getEvents() {
final List < EventsData > eventsList = eventListStream.stream()
.map(mapEvents)
.collect(Collectors.toList());
eventList.add(new EventsData("CodesType", getCodesType()));
eventList.add(new EventsData("SupportType", getSupportType()));
return eventList;
)
You can use
private List<EventsData> getEvents() {
final List<EventsData> eventList = eventListStream.stream()
.filter(type -> type != CodesType.class)
.map(events -> new EventsData(events.getSimpleName(), getType(events)))
.collect(Collectors.toCollection(ArrayList::new));
eventList.add(new EventsData("CodesType", getCodesType()));
eventList.add(new EventsData("SupportType", getSupportType()));
return eventList;
}
private String[] getType(Class<? extends Enum<?>> events) {
return Arrays.stream(events.getEnumConstants())
.map(Enum::name)
.sorted()
.toArray(String[]::new);
}
Instead of declaring a Function
outside the Stream pipeline, I moved the complex part into a named method, which aligns with your already existing methods, getCodesType()
and getSupportType()
.
Instead of collecting into a mutable list, to add the predefined elements, you can also integrate them into the Stream pipeline:
private List<EventsData> getEvents() {
return Stream.concat(
eventListStream.stream()
.filter(type -> type != CodesType.class)
.map(events -> new EventsData(events.getSimpleName(),getType(events))),
Stream.of(new EventsData("CodesType", getCodesType()),
new EventsData("SupportType", getSupportType()))
).collect(Collectors.toList());
}