I'm learning some tricks from Java 8. I created a simple list:
private void createData() {
bottles.add(new Whiskey("Jack Daniels", "PL"));
bottles.add(new Whiskey("Balentains", "PL"));
bottles.add(new Whiskey("Balentains", "EN"));
bottles.add(new Whiskey("Balentains", "EN"));
bottles.add(new Whiskey("Balentains", "GR"));
bottles.add(new Whiskey("Balentains", "PL"));
bottles.add(new Whiskey("Balentains", "GR"));
}
And now I would like to get items from this list by few things. If user give a parameter origin
, I want to filter this list by origins
, but when he gave wrong origin
then he should get empty list and when he won't give origin
parameter then he should get whole list.
I have a method which filtering items in list:
private Optional<List<Whiskey>> getWhiskeyFromCountry(String origin) {
final List<Whiskey> whiskies = bottles.stream()
.filter(b -> b.getOrigin().equals(origin))
.collect(Collectors.toList());
return whiskies.isEmpty() ? Optional.empty() : Optional.of(whiskies);
}
And also a main method which get parameter (or not) and response with result:
private void getAll(RoutingContext routingContext) {
Optional<String> origin = Optional.ofNullable(routingContext.request().params().get("filter"));
List<Whiskey> result = getWhiskeyFromCountry(origin.orElse("")).orElse(Collections.EMPTY_LIST);
routingContext.response()
.putHeader("content-type", "application/json; charset=utf-8")
.end(Json.encodePrettily(origin.isPresent() ? result : bottles));
}
The problem is that I still use if statemant in last line and I do not want do this. I would like to change this code into clear and functional. I tried to do some magic with Optionals but in the end I got this one and I think it can be do better and simpler. Could you help me? Or maybe this code is good and I do not need to change anything? This question is more about clean code.