Stream流
1.定义
- 单从"stream"这个单词来看,它似乎和我们之前学的IO流中的InputStream和OutputStream流有些关系。实际上,没有任何关系!java8新增的Stream流是为了提高程序员在集合的操作
- 要想操作流,首先需要一个数据源,可以是数组或者集合,每次操作都会返回一个新的流对象,方便链式进行操作,但原有的流对象会保持不变。
2.创建流
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
/**
* 通过数据源创建Stream流
* @author Administrator
*
*/
public class Test {
public static void main(String[] args) {
String[] arr = new String[] {"武汉","长沙","南昌","合肥"};
//通过数据源创建stream流对象(数据源可以是数组也可以是集合)
Stream<String> stream = Arrays.stream(arr);
// stream = Stream.of(arr);
stream = Stream.of("武汉","长沙","南昌","合肥");
List<String> list = new ArrayList<>();
list.add("武汉");
list.add("长沙");
list.add("南昌");
list.add("合肥");
stream = list.stream();
//创建stream流操作集合
stream.sorted().forEach(System.out::println);
}
}
3.操作流
-
stream流操作父类:
- filter:接收Lambda表达式,从流中排除某些元素进行操作
- limit:截断流,使其元素不超过给定对象
- skip(n):跳过元素,返回一个扔掉了前n个元素的流,若流中元素不足n个,则返回一个空流,与limit(n)互补
- distinct:去重,通过重写流的hashcode()和equals()方法去除重复元素
-
测试
-
person类
public class Person { private String name; private Integer age; private String country; private char sex; public Person() { super(); } public Person(String name, Integer age, String country, char sex) { super(); this.name = name; this.age = age; this.country = country; this.sex = sex; } 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; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } public char getSex() { return sex; } public void setSex(char sex) { this.sex = sex; } @Override public String toString() { return "Person [name=" + name + ", age=" + age + ", country=" + country + ", sex=" + sex + "]"; } }
-
测试
import java.util.ArrayList; import java.util.List; public class Test { public static void main(String[] args) { List<Person> personList = new ArrayList<Person>(); personList.add(new Person("欧阳雪",18,"中国",'F')); personList.add(new Person("Tom",24,"美国",'M')); personList.add(new Person("Harley",22,"英国",'F')); personList.add(new Person("向天笑",20,"中国",'M')); personList.add(new Person("李康",22,"中国",'M')); personList.add(new Person("小梅",20,"中国",'F')); personList.add(new Person("何雪",21,"中国",'F')); personList.add(new Person("李康",22,"中国",'M')); //案例1:找到年龄大于18岁的人并输出 personList.stream().filter((p)->p.getAge()>18).forEach(System.out::println); //案例2:查找中国人的数量 long count = personList.stream().filter((p)->p.getCountry().equals("中国")).count(); System.out.println("中国人数量"+count); //案例3:找到18岁以上的中国人 personList.stream().filter((p)->p.getCountry().equals("中国")).filter((p)->p.getAge()>18).forEach(System.out::println); System.out.println("=======================1"); //案例4:从集合中取出2个女性 personList.stream().filter((p)->p.getSex()=='F').limit(2).forEach(System.out::println); System.out.println("========================2"); //案例5:从集合中的第二个开始,取出所有女性 personList.stream().filter((p)->p.getSex()=='F').skip(1).forEach(System.out::println); System.out.println("=========================3"); //案例6:从集合的第二个开始,取到两个女性 personList.stream().filter((p)->p.getSex()=='F').skip(1).limit(2).forEach(System.out::println); System.out.println("=================================4"); //案例7:取出所有男性 personList.stream().filter((p)->p.getSex()=='M').distinct().forEach(System.out::println); } }
-
4.stream映射流
4.1 Map
-
Map–用于接收Lambda表达式后将元素转换为其他形式或提取信息,接收一个函数作为参数,该函数会应用到每个元素上,并将其映射成一个新的元素
-
案例1:
-
Person类
public class Person { private String name; private Integer age; private String country; private char sex; public Person() { super(); } public Person(String name, Integer age, String country, char sex) { super(); this.name = name; this.age = age; this.country = country; this.sex = sex; } 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; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } public char getSex() { return sex; } public void setSex(char sex) { this.sex = sex; } @Override public String toString() { return "Person [name=" + name + ", age=" + age + ", country=" + country + ", sex=" + sex + "]"; } }
-
测试
import java.util.ArrayList; import java.util.List; import java.util.stream.Stream; public class Test { public static void main(String[] args) { List<String> list = new ArrayList<String>(); list.add("周杰伦"); list.add("王力宏"); list.add("陶喆"); list.add("林俊杰"); //将函数作为map的参数,返回一个新的类型的流; Stream<Integer> stream = list.stream().map(String::length); stream.forEach(System.out::println); } }
-
-
案例2:
-
PersonCountry类
public class PersonCountry { private String country; public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } @Override public String toString() { return "PersonCountry [country=" + country + "]"; } }
-
测试
import java.util.ArrayList; import java.util.List;
import java.util.stream.Stream;
public class Test2 {
public static void main(String[] args) {
List personList = new ArrayList();
personList.add(new Person(“欧阳雪”,18,“中国”,‘F’));
personList.add(new Person(“Tom”,24,“美国”,‘M’));
personList.add(new Person(“Harley”,22,“英国”,‘F’));
personList.add(new Person(“向天笑”,20,“中国”,‘M’));
personList.add(new Person(“李康”,22,“中国”,‘M’));
personList.add(new Person(“小梅”,20,“中国”,‘F’));
personList.add(new Person(“何雪”,21,“中国”,‘F’));
personList.add(new Person(“李康”,22,“中国”,‘M’));//把personlist集合中的国家列表作为一个新的集合
// Stream stream = personList.stream().map(§->{
// PersonCountry country = new PersonCountry();
// country.setCountry(p.getCountry());
// return country;
// });
// stream.forEach(System.out::println);
//简写如下
//map的作用是将personList集合列表的元素(对象)逐一遍历到每一个对象的country元素并返回成一个新的stream流
personList.stream().map(§->{
PersonCountry country = new PersonCountry();
country.setCountry(p.getCountry());
return country;
}).forEach(System.out::println);
}
} -
4.2 flatMap
-
先看以下案例:
-
TestStreamAPI类
import java.util.ArrayList; import java.util.List; import java.util.stream.Stream; public class TestStreamAPI { /** * 将每个字符串打散,返回该字符串的stream流 * @param str * @return */ public static Stream<Character> getCharacterByString(String str){ List<Character> characterList = new ArrayList<Character>(); for (Character character : str.toCharArray()) { characterList.add(character); } return characterList.stream(); } }
-
测试
import java.util.Arrays; import java.util.List; import java.util.stream.Stream; public class Test { public static void main(String[] args) { List<String> list = Arrays.asList("aaa","bbb","ccc","ddd","dd"); Stream<Stream<Character>> stream = list.stream().map(TestStreamAPI::getCharacterByString); // stream.forEach(System.out::println); //因为TestStreamAPI::getCharacterByString方法返回的是一个流.所以stream是在流里面嵌套了流 //返回的stream是Stream<Stream<Character>>流中流,所以当我们需要打印的时候就必须对流中的每个元素(流)再次遍历 stream.forEach(sm->sm.forEach(System.out::println)); //但我们希望返回的是一个流,而不是流中流?-->flatMap解决该问题 } }
-
使用flatMap
import java.util.Arrays; import java.util.List; import java.util.stream.Stream; public class Test2 { public static void main(String[] args) { List<String> list = Arrays.asList("aaa","bbb","ccc","ddd","dd"); //flatMap在接收到stream后,会将接收到的stream中的每个元素取出来放入一个stream流中,最后将一个包含多个元素的stream返回 Stream<Character> stream = list.stream().flatMap(TestStreamAPI::getCharacterByString); stream.forEach(System.out::println); } }
-
Map和flatMap的区别:
-
map在接收到流后,直接将stream流放入到一个stream流中,最终整体返回一个包含了多个stream流的stream流,如图1
图1:
-
flatMap流在接收到stream流后,会将接收到的stream流中的每个元素取出来放到一个stream中,最后返回一个包含多个元素的stream流,如图2
图2:
5.stream排序
-
自然排序
import java.util.Arrays; import java.util.List; /** * 排序 * @author Administrator * */ public class Test { public static void main(String[] args) { List<Integer> list = Arrays.asList(1,45,78,41,4); list.stream().sorted().forEach(System.out::println); } }
-
定制排序
-
person类
public class Person { private String name; private Integer age; private String country; private char sex; public Person() { super(); } public Person(String name, Integer age, String country, char sex) { super(); this.name = name; this.age = age; this.country = country; this.sex = sex; } 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; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } public char getSex() { return sex; } public void setSex(char sex) { this.sex = sex; } @Override public String toString() { return "Person [name=" + name + ", age=" + age + ", country=" + country + ", sex=" + sex + "]"; } }
-
测试
import java.util.ArrayList; import java.util.List; public class Test2 { public static void main(String[] args) { List<Person> personList = new ArrayList<Person>(); personList.add(new Person("欧阳雪",18,"中国",'F')); personList.add(new Person("Tom",24,"美国",'M')); personList.add(new Person("Harley",22,"英国",'F')); personList.add(new Person("向天笑",20,"中国",'M')); personList.add(new Person("李康",22,"中国",'M')); personList.add(new Person("小梅",20,"中国",'F')); personList.add(new Person("何雪",21,"中国",'F')); personList.add(new Person("李康",22,"中国",'M')); personList.stream().sorted((p1,p2)->{ // return p1.getAge()-p2.getAge(); return p1.getAge().compareTo(p2.getAge()); }).forEach(System.out::println); } }
-
6.查找与匹配
1.allMatch()–检查是否匹配所有元素
2,anyMatch()–检查是否至少匹配一个元素
3.noneMatch()–检查是否没有匹配所有元素
4.findFirst()–返回第一个元素
5.findAny()–返回当前流中的任意元素
6.count()–返回流中元素的总个数
7.max()–返回流中最大值
8.min()–返回流中最小值
…详细参考API
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;
public class Test {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("周杰伦");
list.add("王力宏");
list.add("陶喆");
list.add("林俊杰");
boolean flag = list.stream().anyMatch(ele->ele.contains("王"));
System.out.println("是否包含王同学"+flag);
boolean flag2 = list.stream().allMatch(ele->ele.length()>1);
System.out.println("姓名长度都大于1个吗?"+flag2);
boolean flag3 = list.stream().noneMatch(ele->ele.endsWith("杰"));
System.out.println("姓名中没有一个以杰结尾?"+flag3);
}
}
7.计算
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
public class Test {
public static void main(String[] args) {
Integer[] ints = {0,1,2,3};
List<Integer> list = Arrays.asList(ints);
Optional<Integer> optional = list.stream().reduce((a,b)->a+b);
Optional<Integer> optional2 = list.stream().reduce(Integer::sum);
System.out.println(optional.orElse(0));//如果有返回值就返回a+b的值,否则返回0
System.out.println(optional2.orElse(100));
//第一个参数代表起始值,从起始值5+6=11
int num1 = list.stream().reduce(5,(a,b)->a+b);
System.out.println(num1);
}
}
8.Collect()方法将流转换成集合或者数组
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class CollectStreamDemo {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("周杰伦");
list.add("王力宏");
list.add("陶喆");
list.add("林俊杰");
//通过stream流对集合进行操作后再次转换成数组
String[] strArray = list.stream().sorted().toArray(String[]::new);
System.out.println(Arrays.toString(strArray));
//通过stream流对集合进行操作后再次转换成list集合
List<Integer> list1 = list.stream().map(String::length).collect(Collectors.toList());
System.out.println(list1.toString());
List<String> list2 = list.stream().sorted().collect(Collectors.toCollection(ArrayList::new));
System.out.println(list2.toString());
}
}