您的位置:首页 > 编程语言 > Java开发

Java8 Stream 基本操作示例

2017-07-06 16:52 543 查看
package Stream;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.IntSummaryStatistics;
import java.util.List;
import java.util.Optional;
import java.util.OptionalInt;
import java.util.stream.Collectors;

public class Java8Stream {
public static void main(String[] args) {
System.out.println("hello Stream");
List<Person> list=getPersoms();

//调用Stream(流)API函数
//List<Person> studentList
boolean isAllMatch=list.stream().allMatch(Person::isStudent);
boolean isAnyMatch=list.stream().anyMatch(Person::isStudent);
boolean isALLNotMatch=list.stream().noneMatch(Person::isStudent);
System.out.println("is All student? "+isAllMatch);
System.out.println("is Any student? "+isAnyMatch);
System.out.println("is no student? "+isALLNotMatch);

List<String> studentList=list.stream().
filter(Person::isStudent).//筛选出学生
//map((Person person)->person.getName()).//获取学生名字形成新的流
map(Person::getName).
collect(Collectors.toList());//将新的流返回给studentList
System.out.println("studentList: "+studentList);

//flatMap
List<String> strlist=new ArrayList<String>();
strlist.add("I am a boy");
strlist.add("I love the girl");
strlist.add("But the girl loves another girl");

List<String> resultlist=strlist.stream().
map(line->line.split(" ")).//转化为String[]
flatMap(Arrays::stream).//转化为Stream
distinct().//去除重复的String
collect(Collectors.toList());//返回集合
System.out.println("resultlist: "+resultlist);

//获取第一个元素findFirst
Optional<Person> person = list.stream().findFirst();
System.out.println("findFirst: "+person.get());

OptionalInt maxAge  =list.stream().mapToInt(Person::getAge).max();
System.out.println("maxAge: "+maxAge.getAsInt());

IntSummaryStatistics all=list.stream().collect(
b83b
Collectors.summarizingInt(Person::getAge));

System.out.println("sumAge:"+all.getSum()+"   aver"+all.getAverage()
+"   minAge"+all.getMin()+"   maxAge"+all.getMax());
}

/**
* 测试数据
* @return
*/
public static List<Person> getPersoms(){
List<Person> list=new ArrayList<Person>();
Person person;
for(int i=0;i<10;i++){
person=new Person();
person.setAge(i);
person.setName("lice"+String.valueOf(i));
person.setStudent(true);
list.add(person);
}
return list;
}

/**
* 测试数据
* @return
*/
public static List<Integer> getNumbers(){
List<Integer> list=new ArrayList<Integer>();
for(int i=0;i<10;i++)
list.add(i);
return list;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java