获取流

根据List获取流

1
2
ArrayList<Object> list = new ArrayList<>();
Stream<Object> stream = list.stream();

根据Set集合获取流

1
2
HashSet<Object> set = new HashSet<>();
Stream<Object> stream = set.stream();

根据Map集合获取流

根据键获取流

1
2
HashMap<Object, Object> map = new HashMap<>();
Stream<Object> stream = map.keySet().stream();

根据值获取流

1
2
HashMap<Object, Object> map = new HashMap<>();
Stream<Object> stream = map.values().stream();

根据键值对对象获取值

1
2
HashMap<Object, Object> map = new HashMap<>();
Stream<Map.Entry<Object, Object>> stream = map.entrySet().stream();

根据数组获取流

1
2
String[] strs = new String[]{"a","b","c"};
Stream<String> stream = Stream.of(strs);

常用方法

终结方法:返回值类型不再是Stream接口本身类型的方法

非终结方法(延迟方法):返回值类型仍然是Stream接口自身类型的方法,除了终结方法都是延迟方法

count方法

long count();:统计流中的元素,返回long类型数据

1
2
ArrayList<Object> list = new ArrayList<>();
long count = list.stream().count();

forEach方法

void forEach(Consumer<? super T> action):逐一处理流中的元素

1
2
3
4
5
6
7
ArrayList<String> list = new ArrayList<>();
list.add("a");
list.add("b");
list.add("c");
list.forEach((String str)->{
System.out.println(str);
});

filter方法

Stream<T> filter(Predicate<? super ?> predicate):过滤出满足条件的元素

1
2
3
4
5
6
7
Stream<String> stream = Stream.of("abc", "bbc", "cba", "aac");
stream.filter((String str)->{
//过滤出所有以"a"开头的字符串
return str.startsWith("a");
}).forEach((String str)->{
System.out.println(str);
});

limit方法

Stream<T> limit(long maxSize):取用前几个元素

注意:参数是一个long 类型,如果流的长度大于参数,则进行截取;否则不进行操作

1
2
3
4
5
Stream<String> stream = Stream.of("abc", "bbc", "cba", "aac");
//获取流中前三个元素
stream.limit(3).forEach((String str)->{
System.out.println(str);
});

skip方法

Stream<T> skip(long n):跳过前几个元素

1
2
3
4
5
Stream<String> stream = Stream.of("abc", "bbc", "cba", "aac");
//跳过前3个元素
stream.skip(3).forEach((String str)->{
System.out.println(str);
});

concat方法

public static <T> Stream<T> concat(Stream<? extends T> a, Stream<? extends T> b):合并两个流

1
2
3
4
5
6
Stream<String> stream1 = Stream.of("abc", "bbc", "cba", "aac");
Stream<Integer> stream2 = Stream.of(1,2,3);
Stream<? extends Serializable> stream = Stream.concat(stream1, stream2);
stream.forEach((Object res)->{
System.out.println(res);
});

map方法

将流中的元素进行再次加工形成一个新流,流中的每一个元素映射为另外的元素

1
2
3
4
5
6
Stream<String> stream = Stream.of("1","2","3");
stream.map((String str)->{
return Integer.parseInt(str);
}).forEach((Integer num)->{
System.out.println(num);
});

collect() 方法

收集流中的数据到集合或者数组中去

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
Stream<String> stream = Stream.of("a", "b", "c");
//收集流中的数据到list中
List<String> list = stream.collect(Collectors.toList());

//收集流中的数据到set
Set<String> set = stream.collect(Collectors.toSet());

//收集流中的数据到指定集合中(此处是ArrayList)
ArrayList<String> arrayList = stream.collect(Collectors.toCollection(ArrayList::new));

//收集 Stream 流中的数据到数组中 使用 toArray()无参
//注意:此处的strs1默认为Object[]无法获取length等参数
//可以将其强转为String[]
Object[] strs1 = stream.toArray();

//收集 Stream 流中的数据到数组中 使用有参返回指定类型数组
String[] strs2 = stream.toArray(String[]::new);

Stream流中数据聚合/分组/分区/拼接操作

先创建一个实体类Student方便进行演示

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
>public class Student {

private String name; //名字
private int age; //年龄
private int score; //分数
public Student(String name, int age, int score) {
this.name = name;
this.age = age;
this.score = score;
}

public String getName() { return name; }
public void setName(String name) { this.name = name; }
public int getAge() { return age; }
public void setAge(int age) { this.age = age; }
public int getScore() { return score; }
public void setScore(int score) { this.score = score; }

@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
", score=" + score +
'}';
}

聚合操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
Stream<Student> studentStream = Stream.of(
new Student("A", 10, 90),
new Student("B", 12, 92),
new Student("C", 14, 94),
new Student("D", 16, 96)
);
//1、获取分数最大值
Optional<Student> max = studentStream.collect(Collectors.maxBy((s1, s2) -> {
return s1.getScore() - s2.getScore();
}));
//化简后
// Optional<Student> max = studentStream.max(Comparator.comparingInt(Student::getScore));

//2、求年龄平均值
Double age = studentStream.collect(Collectors.averagingInt(Student::getAge));

//3、统计学生数量
Long count = studentStream.collect(Collectors.counting());

分组操作

1
2
3
4
5
6
7
8
9
10
11
//1、按照年龄进行分组
Map<Integer, List<Student>> map1 = studentStream.collect(Collectors.groupingBy(Student::getAge));
map1.forEach((key,value)->{
System.out.println(key+":"+value);
});
/**
* 16:[Student{name='D', age=16, score=96}]
* 10:[Student{name='A', age=10, score=90}]
* 12:[Student{name='B', age=12, score=92}]
* 14:[Student{name='C', age=14, score=94}]
*/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
//2、将分数大于90的分为优秀,小于90分为良
Map<String, List<Student>> map2 = studentStream.collect(Collectors.groupingBy(s->{
if (s.getScore()>90){
return "优秀";
}else {
return "良";
}
}));
map2.forEach((key,value)->{
System.out.println(key+":"+value);
});
/**
* 优秀:[Student{name='B', age=12, score=92}
* Student{name='C', age=14, score=94}
* Student{name='D', age=16, score=96}]
* 良:[Student{name='A', age=10, score=90}]
*/