Java8新特性 1——利用流和Lambda操作集合
阿新 • • 發佈:2019-01-22
Java8中可以用簡潔的程式碼來操作集合,比如List,Map,他們的實現ArrayList。以此來實現Java8的充分利用CPU的目標。
流和Lambda表示式都是Java8中的新特性。流可以實現對集合的遍歷,過濾,聚合,求和以及求平均值等操作。文章力求好懂的基礎上寫得簡潔,達到看完就能用的效果。
1:利用流和Lambda來遍歷集合
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
List<People> peoples=new ArrayList<People>();
peoples.add(new People("愛因斯坦", 100));
peoples.add(new People("牛頓", 80));
//stream()方法得到一個流
peoples.stream()
.forEach(p->{System.out.println(p.getName());});
}
}
class People{
private String name;
private Integer age;
public People(String name, Integer age) {
super();
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
輸出如如下:
因斯坦
牛頓
霍金
2:利用流對集合進行過濾
過濾選取70歲以上的科學家
Predicate<People> predicate=p->p.getAge()>70;
peoples.stream()
.filter(predicate)
.forEach(p->{System.err.println(p.getName());});
輸出結果如下:
愛因斯坦
牛頓
3:利用流對集合進行聚集
long len=peoples.stream()
.count();
System.out.println(len);
輸出
3
4:利用流對集合進行求和
long sum=peoples.stream()
.mapToInt(p->p.getAge())
.sum();
System.out.println(sum);
輸出
230
5:利用流對集合求平均值
因為求平均值會出現除數為0的情況,所以返回值是Optional
OptionalDouble sum=peoples.stream()
.mapToInt(p->p.getAge())
.average();
if(sum.isPresent())
System.out.println(sum.getAsDouble());
else {
System.out.println("error");
}
輸出如下;
76.66666666666667
6:利用流運算元組
可以利用Arrays.stream()方法得到一個stream或者用Stream.of()得到Stream物件,後面的操作和上面講解的一樣操作。
//運算元組
People[] peoples2={new People("愛因斯坦", 100),new People("牛頓", 80),new People("霍金", 50)};
//Stream<People> stream=Stream.of(peoples2);
Stream<People> stream=Arrays.stream(peoples2);
stream.forEach(p->System.out.println(p.getName()));
輸出;
愛因斯坦
牛頓
霍金