初识stream
1、对于迭代来说,包含内部迭代和外部迭代。
外部迭代 内部迭代外部迭代:(程序逻辑自己控制迭代过程)
int count = 0;
Iterator<Artist> iterator = allArtists.iterator();
while(iterator.hasNext()) {
Artist artist = iterator.next();
if (artist.isFrom("London")) {
count++;
}
}
内部迭代:(相当于函数回调,将方法传入给java库类内部,由库内部来回调你的接口函数)
package org.java8.stream;
import java.util.ArrayList;
import java.util.Collection;
public class StreamTest {
public static void main(String[] args) {
Collection<Artist> allArtists = new ArrayList<>();
Artist test = new Artist();
test.setFrom("London");
allArtists.add(test);
//遍历放在内部,将方法传入到内部作为函数进行调用
long count = allArtists.stream()
.filter(artist -> artist.isFrom("London"))
.count();
System.out.println(count);
allArtists.stream()
.filter(artist ->{
System.out.println("no print");//打印不出来,因为并没有具体的进行计算,判断计算方法是看返回的还是不是stream类型
return artist.isFrom("London");
});
}
static class Artist {
String name;
String from;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isFrom(String from) {
return this.from.equalsIgnoreCase(from);
}
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
}
}
网友评论