长期汇总Stream的使用技巧。
创建stream的常用方法
- 通过Collection.stream()来生成
List<String> list = Arrays.asList(new String[] {"ab", "bc", "ab", "cd", "bc", "ed", "ae"});
list.stream().sorted().forEach(System.out::println);
- 通过数组来生成,Arrays.stream()或者Stream.of()
if (Arrays.stream(new String[] {"ab", "bc", "ab", "cd", "bc", "ed", "ae"})
.anyMatch(n -> n == "ab"))
System.out.println("exists");
和
System.out.println(
Stream.of(new Integer[] {1, 2, 3, 4, 5, 6, 7, 8, 9}).reduce(0, (a, b) -> a + b));
- 使用stream builder来生成
Stream<String> b = Stream.<String>builder().add("ef").add("fg").add("eg").add("gh").build();
b.forEach(System.out::println);
- 使用stream iterate来生成
Stream.iterate(1, i -> i + 1).limit(5).forEach(System.out::println);
- 使用stream generate来生成
Stream.generate(UUID::randomUUID).limit(5).forEach(System.out::println);
- 使用IntStream.range(..)来生成
IntStream.range(1, 20).forEach(i -> {
i = i + 10;
System.out.println(i);
});
- 读取文件来生成stream
文件是
Code,firstName,lastName,age
1,Chris,Riley,35
2,Harold,Campbell,50
3,Jessica,Nichols,30
4,Catherine,Brown,40
5,Kelly,Frazier,60
6,Dennis,Howard,35
try {
BufferedReader br = Files.newBufferedReader(Paths.get("c:\\temp\\1.txt"));
Stream<String> lines = br.lines();
List<Person> persons = lines.skip(1).map(line -> {
String[] arr = line.split(",");
return new Person(arr[1], arr[2], Integer.parseInt(arr[3].trim()));
}).collect(Collectors.toList());
persons.forEach(System.out::println);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Person类
/**
* Copyright: 2021 Hswfit. All rights reserved.
*
* @Title: Person.java
* @Prject: hellotest
* @Package: com.test.hello
* @Description: TODO
* @author: Jay
* @version: V1.0
*/
package com.test.hello;
/**
* @ClassName: Person
* @Description: TODO
* @author: Jay
* @date: 2021-10-19
*/
public class Person {
@Override
public String toString() {
return "Person [firstName=" + firstName + ", lastName=" + lastName + ", age=" + age + "]";
}
/**
* @Title:Person
* @Description:TODO
* @param firstName
* @param lastName
* @param age
*/
public Person(String firstName, String lastName, Integer age) {
super();
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
/**
* @return the firstName
*/
public String getFirstName() {
return firstName;
}
/**
* @param firstName the firstName to set
*/
public void setFirstName(String firstName) {
this.firstName = firstName;
}
/**
* @return the lastName
*/
public String getLastName() {
return lastName;
}
/**
* @param lastName the lastName to set
*/
public void setLastName(String lastName) {
this.lastName = lastName;
}
/**
* @return the age
*/
public Integer getAge() {
return age;
}
/**
* @param age the age to set
*/
public void setAge(Integer age) {
this.age = age;
}
private String firstName;
private String lastName;
private Integer age;
}
输出结果为
Person [firstName=Chris, lastName=Riley, age=35]
Person [firstName=Harold, lastName=Campbell, age=50]
Person [firstName=Jessica, lastName=Nichols, age=30]
Person [firstName=Catherine, lastName=Brown, age=40]
Person [firstName=Kelly, lastName=Frazier, age=60]
Person [firstName=Dennis, lastName=Howard, age=35]
Stream.reduce技巧
- 查找最大值
System.out.println(Stream.of(new Integer[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10})
.reduce(0,(a, c) -> a > c ? a : c));
10
- 查找最长字符串
System.out.println(Stream.of(new String[] {"abc", "cdfe", "abcdefg"}).reduce("",
(String a, String c) -> a.length() > c.length() ? a : c));
abcdefg
- 在字符串数组中,查找字符串是否存在
if (Arrays.stream(new String[] {"ab", "bc", "ab", "cd", "bc", "ed", "ae"})
.anyMatch(n -> n == "ab"))
System.out.println("exists");
exists
- 字符串数组合并成一个字符串
System.out.println(Stream.of(new String[] {"ab", "cd", "ef", "gh", "lm"}).reduce("",
(a, b) -> a + "|" + b));
|ab|cd|ef|gh|lm
- 统计所有人员的年龄合计
System.out.println(personList.stream().
map(x -> x.getAge()).
reduce(0, (a, b) -> a + b));
Stream.collect技巧
- 将所有元素放入不同容器
将元素分别归纳进可变容器 List、Map、Set、Collection 或者ConcurrentMap 。
Collectors.toList();
Collectors.toMap();
Collectors.toSet();
Collectors.toCollection();
Collectors.toConcurrentMap();
- 巧用Collectors.joining
//abcdefghlm
System.out.println(Stream.of(new String[] {"ab", "cd", "ef", "gh", "lm"})
.collect(Collectors.joining()));
//ab,cd,ef,gh,lm
System.out.println(Stream.of(new String[] {"ab", "cd", "ef", "gh", "lm"})
.collect(Collectors.joining(",")));
//[ab,cd,ef,gh,lm]
System.out.println(Stream.of(new String[] {"ab", "cd", "ef", "gh", "lm"})
.collect(Collectors.joining(",", "[", "]")));