我刚刚开始使用Java 8 lambdas,我正在尝试实现我在函数式语言中习惯的一些东西.
例如,大多数函数式语言都有某种类型的查找函数,这些函数对序列进行操作,或者列表返回谓词所在的第一个元素true.我在Java 8中实现这一目标的唯一方法是:
lst.stream()
.filter(x -> x > 5)
.findFirst()
Run Code Online (Sandbox Code Playgroud)
然而这对我来说似乎效率低下,因为过滤器会扫描整个列表,至少根据我的理解(这可能是错误的).有没有更好的办法?
使用外部迭代时,Iterable我们使用break或return来自增强型for-each循环:
for (SomeObject obj : someObjects) {
if (some_condition_met) {
break; // or return obj
}
}
Run Code Online (Sandbox Code Playgroud)
我们如何在Java 8 lambda表达式中使用break或return使用内部迭代,如:
someObjects.forEach(obj -> {
//what to do here?
})
Run Code Online (Sandbox Code Playgroud) 如何获得与流中的条件匹配的第一个元素?我试过这个但是没用
this.stops.stream().filter(Stop s-> s.getStation().getName().equals(name));
Run Code Online (Sandbox Code Playgroud)
该条件不起作用,filter方法在Stop之外的其他类中调用.
public class Train {
private final String name;
private final SortedSet<Stop> stops;
public Train(String name) {
this.name = name;
this.stops = new TreeSet<Stop>();
}
public void addStop(Stop stop) {
this.stops.add(stop);
}
public Stop getFirstStation() {
return this.getStops().first();
}
public Stop getLastStation() {
return this.getStops().last();
}
public SortedSet<Stop> getStops() {
return stops;
}
public SortedSet<Stop> getStopsAfter(String name) {
// return this.stops.subSet(, toElement);
return null;
}
}
import java.util.ArrayList;
import java.util.List;
public class Station {
private final …Run Code Online (Sandbox Code Playgroud)