我正在从Java 8学习一些技巧。
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"));
}现在,我想从这个列表中得到几个项目。如果用户给出一个参数origin,我想通过origins过滤这个列表,但是当他给错了origin时,他应该得到空列表,当他不给origin参数时,他应该得到整个列表。
我有一种方法可以过滤列表中的项目:
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);
}并给出了获取参数(或不求参数)和响应结果的主要方法:
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));
}问题是,我仍然在最后一行使用if状态,我不想这样做。我想将此代码转换为清晰和实用的代码。我试着用选项来做一些魔术,但最终我得到了这个,我认为它可以做得更好,更简单。你能帮我一下吗?或者这段代码很好,我不需要改变什么?这个问题更多的是关于干净的代码。
发布于 2019-10-19 19:55:42
可以使此方法getWhiskeyFromCountry以接受Optional<String>作为参数。
private List<Whiskey> getWhiskeyFromCountry(Optional<String> origin)如果可选的是空返回空列表或基于filter的返回列表,如果用户输入了错误的origin,则会得到空列表。
return origin.map(o->bottles.stream()
.filter(b -> b.getOrigin().equals(o))
.collect(Collectors.toList())).orElse(Collections.EMPTY_LIST);或者在上面的代码中,您可以做一些小的调整,以返回此方法的List getWhiskeyFromCountry。
private List<Whiskey> getWhiskeyFromCountry(String origin) {
return bottles.stream()
.filter(b -> b.getOrigin().equals(origin))
.collect(Collectors.toList());
}而在主要的方法中使用Optional.map
Optional<String> origin = Optional.ofNullable(routingContext.request().params().get("filter"));
List<Whiskey> result = origin.map(o->getWhiskeyFromCountry(o))
.orElse(bottles);https://stackoverflow.com/questions/58467428
复制相似问题