1、操作集合
示例1:
public static void main(String[] args) {
//通过集合创建
List depts = DB.getDepts();
//筛选filter
depts.stream().filter(item->item.getDname().length()>3).forEach(System.out::println);
System.out.println();
//去重distince
Stream.of("aa","bb","cc","bb","11","aa").distinct().forEach(System.out::println);
System.out.println();
//截取limit
Stream.of("aa","bb","cc","bb","11","aa").limit(3).forEach(System.out::println);
System.out.println();
//跳过skip
Stream.of("aa","bb","cc","bb","11","aa").skip(3).forEach(System.out::println);
System.out.println();
//是否匹配任一元素anyMath:判断流中是否存在至少一个元素满足指定的条件
boolean res1 = Stream.of("aa", "bb", "cc", "bb", "11", "aa").anyMatch(item -> item.length() == 3);
System.out.println(res1);
System.out.println();
//是否匹配所有元素allMatch:用于判断流中的所有元素是否都满足指定条件
boolean res2 = Stream.of("aa", "bb", "cc", "bbb", "11", "aa").allMatch(item -> item.length() == 2);
System.out.println(res2);
System.out.println();
//是否所有元素都不匹配noneMatch:与allMatch恰恰相反,用于判断流中的所有元素是否都不满足指定条件
boolean res3 = Stream.of("aa", "bb", "cc", "bb", "11", "aa").noneMatch(item -> item.length() == 3);
System.out.println(res3);
System.out.println();
//获取任一元素findAny:从流中随便选一个元素出来,它返回一个Optional类型的元素
Optional any = DB.getDepts().stream().findAny();
System.out.println(any.get());
System.out.println();
//获取第一个元素findFirst
Optional first = DB.getDepts().stream().findFirst();
System.out.println(first.get());
}
示例2:
public static void main(String[] args) {
// 映射Map:对流中的每个元素执行函数,使得元素转换成另一种类型输出。流会将每一个元素输送给map函数,并执行map中
// 的Lambda表达式,最后将执行结果存入一个新的流中。
DB.getDepts().stream().map(Dept::getDname).forEach(System.out::println);
//归约Reduce:归约是将集合中的所有元素经过指定运算,折叠成一个元素输出,如:求最值、平均数等
Optional empOpt = DB.getEmps().stream().reduce((emp1, emp2) -> emp1.getSal() > emp2.getSal() ? emp1 : emp2);
System.out.println(empOpt.get());
int res = Stream.of("zhangsan", "lisi", "wanger", "mazi")
.reduce(0, //初始值
(sum, str) -> sum + str.length(), //累加器 //
(a, b) -> a + b //部分拼接器,并行执行时才会用到
);
System.out.println(res);
}
示例3:求List中出现的单词
public static void main(String[] args) {
List list = new ArrayList();
list.add("See you tomorrow");
list.add("I will call the roll before class");
list.add("Have I made myself clear");
//1、分词:分词之后每个元素变成了一个String[]数组
Stream stream1 = list.stream().map(line -> line.split(" "));
//2、将分词后得到的数组转换成流
Stream stream2 = stream1.flatMap(Arrays::stream);
//3、去重
Stream stream3 = stream2.distinct();
stream3.forEach(System.out::println);
}
结果:
对于对象数组,Arrays.stream 和 Stream.of 都返回相同的输出。原因是对于对象数组,Stream.of 内部调用了 Arrays.stream 方法。 对于基本数组,Arrays.stream 和 Stream.of 将返回不同的输出。 推荐使用 Arrays.stream,不需要考虑是对象数组还是基本数组,直接返回对应的流对象,操作方便。
示例1 :生成随机数组public static void main(String[] args) {
int[] digits1 = new Random().ints(10, 99).limit(8).toArray();
System.out.println(Arrays.toString(digits1));
int[] digits2 = new Random().ints(8, 10, 99).toArray();
System.out.println(Arrays.toString(digits2));
}
示例2: 数组转Stream
public static void main(String[] args) {
//基本数组
int[] digits = {1,3,5,7,9};
IntStream stream1 = Arrays.stream(digits);
stream1.forEach(System.out::println);
Stream temp = Stream.of(digits);
//不能直接输出,需要先转换为IntStream
IntStream stream2= temp.flatMapToInt(item -> Arrays.stream(item));
stream2.forEach(System.out::println);
//对象数组
Dept[] depts = {new Dept(10,"ACCOUNTING","NEWYORK"),new Dept(20,"RESEARCH","DALLAS"),new Dept(30,"SALES","CHICAGO"),new Dept(40,"OPERATIONS","BOSTON")};
Stream stream3 = Arrays.stream(depts);
stream3.forEach(System.out::println);
Stream stream4 = Stream.of(depts);
stream4.forEach(System.out::println);
}
示例3 :List转数组
public static void main(String[] args) {
List list =Arrays.asList(1,8,3,2,10,4,9,7,6);
//实现一:
Integer[] array1 = list.stream().toArray(Integer[]::new);
System.out.println(Arrays.toString(array1));
//实现二:
Integer[] array2 = list.stream().toArray(size -> new Integer[size]);
System.out.println(Arrays.toString(array2));
}
3、操作Optional
示例3.1:获取对象指定属性值
public static void main(String[] args) {
Optional.ofNullable(new Dept(20, "sales", "newyork"))
.stream()
.map(Dept::getDname)
.forEach(System.out::println);
}
4、操作文件
public static void main(String[] args) {
Path path = Paths.get("pom.xml");
//输出文件内容
Stream lines = null;
try {
lines = Files.lines(path)
.onClose(() -> System.out.println("流自动关闭了"));//测试Stream的close()是否触发
} catch (IOException e) {
e.printStackTrace();
}
lines.forEach(System.out::println);
lines.close(); // 流用来操作文件的时候才需要手动关闭,单独使用Stream不需要关闭
//获取长度大于90的第一行
try(Stream stream = Files.lines(path).filter(item -> item.trim().length() > 90);){
Optional opt = stream.findFirst();
if (opt.isPresent()) {
System.out.println(opt.get());
}
}catch (IOException e){
e.printStackTrace();
}
//找出文件最长一行的长度
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("pom.xml"));
int longest = br.lines()
.mapToInt(String::length)
.max()
.getAsInt();
System.out.println(longest);
} catch (FileNotFoundException e) {
e.printStackTrace();
}finally {
if(br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}