Java8 新特性 stream 内的简单方法的介绍
import org.junit.Test;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* @author gdl
*/
public class StreamTest {
@Test
public void sortedTest() {
List<Integer> words = Arrays.asList(1, 2, 3, 5, 4, 8, 6, 7, 7);
//1.forEach 将指定的集合遍历输出
System.out.println("将指定的集合遍历输出");
words.stream().forEach(System.out::println);
//2.filter 根据条件输出
System.out.println("输出大于5的数值");
words.stream().filter(o -> o > 5).forEach(System.out::println);
//3.findFirst 获取第一个 get()用于获取Optional(Java8对象)内的值
System.out.println("获取第一个大于5的值(有Optional对象)");
System.out.println(words.stream().filter(o -> o > 5).findFirst());
System.out.println("获取第一个大于5的值(无Optional对象)");
System.out.println(words.stream().filter(o -> o > 5).findFirst().get());
//4.sorted 排序,根据指定要求
System.out.println("根据排序规则进行排序");
words.stream().sorted((o1, o2) -> {
if (o1 > o2) {
return 1;
} else if (o1 < o2) {
return -1;
} else {
return 0;
}
}).forEach(System.out::println);
//5.distinct 数据去重操作
System.out.println("数据去重");
words.stream().distinct().forEach(System.out::println);
//6.findAny 获取集合大于 5 的 值(未排序)
System.out.println("获取大于 5 的任意值");
System.out.println(words.stream().filter(o -> o > 5).findFirst().get());
//7 .toMap 将List对象转换为Map
System.out.println("将list集合转为map");
List<Student> students = Arrays.asList(new Student(1,"小明"),new Student(2,"小王"),new Student(3,"小红"));
Map<Integer, String> studentMap = students.stream().collect(Collectors.toMap(Student::getId, Student::getName));
System.out.println(studentMap);
//8.skip/limit
System.out.println("skip跳过5个数值");
words.stream().skip(5).forEach(System.out::println);
System.out.println("limit限制显示3个数值");
words.stream().limit(3).forEach(System.out::println);
}
}
class Student {
private Integer id;
private String name;
public Student(Integer id, String name) {
this.id = id;
this.name = name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
输出结果:
将指定的集合遍历输出
1
2
3
5
4
8
6
7
7
输出大于5的数值
8
6
7
7
获取第一个大于5的值(有Optional对象)
Optional[8]
获取第一个大于5的值(无Optional对象)
8
根据排序规则进行排序
1
2
3
4
5
6
7
7
8
数据去重
1
2
3
5
4
8
6
7
获取大于 5 的任意值
8
将list集合转为map
{1=小明, 2=小王, 3=小红}
skip跳过5个数值
8
6
7
7
limit限制显示3个数值
1
2
3