1、建立Stream
2、Stream筛选和切片
3、Stream映射
4、Stream排序
5、Stream查找与匹配
6、Stream约与收集归
7、Stream约操练
1、建立Stream
package com.stream.api1;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
import org.junit.Test;
/**
* 一 、 Stream 的三个操作步调 1、建立Stream 2、中级操作 3、终止操作(终端操作)
*
* @author Administrator
*
*/
public class TestStreamAPI1 {
// 建立Stream
@Test
public void test1() {
// 1、可以经由过程Collection 系列调集供给的stream()或parallelStream()
List<String> list = new ArrayList<String>();
Stream<String> stream1 = list.stream();
// 2、经由过程Arrays中的静态方式stream()获取数组流
Employee[] ems = new Employee[10];
Stream<Employee> stream2 = Arrays.stream(ems);
// 3、经由过程Stream类中的静态方式of()
Stream<String> stream3 = Stream.of("aa", "bb", "cc", "dd");
// 4、建立无限流
Stream<Integer> stream4 = Stream.iterate(0, x -> x + 2);
// stream4.forEach(System.out::println);
stream4.limit(10).forEach(System.out::println);
// 生当作
Stream.generate(() -> Math.random()).limit(5).forEach(System.out::println);
}
}
2、Stream筛选和切片
package com.stream.api2;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Stream;
import org.junit.Test;
import com.stream.api1.Employee;
/**
* 一 、 Stream 的三个操作步调 1、建立Stream 2、中级操作 3、终止操作(终端操作)
*
* @author Administrator
*
*/
public class TestStreamAPI2 {
List<Employee> employees = Arrays.asList(new Employee("张三", 12, 1200.99), new Employee("小明", 15, 4500.99),
new Employee("小丽", 16, 5500.99), new Employee("王二", 32, 1100.99), new Employee("二虎", 22, 9825.99),
new Employee("李静", 18, 4502.99), new Employee("小三", 17, 1469.99), new Employee("小三", 17, 1469.99),
new Employee("小三", 17, 1469.99), new Employee("小三", 17, 1469.99));
// 中心操作
/**
* 筛选与切片 filter —— 接收Lambda,从流中解除某些元素 limit —— 截断流,使其元素不跨越给定命量。 skip(n) ——
* 跳过元素,返回一个扔失落了前n个元素的流。若流中元素不足n个,则返回一个空流。与limit(n)互补 distinct ——
* 筛选,经由过程流所生当作元素的hashCode()和equals()去除反复元素
*
*
* 注重:利用distinct去重需要重写hashcode和equals方式
*/
// 内部迭代:迭代操作有Stream API完当作。
@Test
public void test1() {
// 中心操作:不会执行任何操作
Stream<Employee> stream1 = employees.stream().filter((e) -> {
System.out.println("Stream API中心操作");
return e.getAge() > 17;
});
// 终止操作:一次性执行全数内容,即“惰性求值”
stream1.forEach(System.out::println);
}
// 外部迭代
@Test
public void test2() {
Iterator<Employee> it = employees.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
}
// 短路,limit一旦找到合适的数据将不再继续执行,必然水平上提高了机能
@Test
public void test3() {
employees.stream().filter((e) -> {
System.out.println("短路!");
return e.getSalary() > 5000;
}).limit(2).forEach(System.out::println);
;
}
@Test
public void test4() {
employees.stream().filter((e) -> e.getSalary() > 1000).skip(2).limit(2).forEach(System.out::println);
;
}
@Test
public void test5() {
employees.stream().filter((e) -> e.getSalary() > 1000).skip(2).distinct().forEach(System.out::println);
;
}
}
/3、Stream映射
package com.stream.api3;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
import org.junit.Test;
import com.stream.api1.Employee;
public class TestStreamAPI3 {
List<Employee> employees = Arrays.asList(new Employee("张三", 12, 1200.99), new Employee("小明", 15, 4500.99),
new Employee("小丽", 16, 5500.99), new Employee("王二", 32, 1100.99), new Employee("二虎", 22, 9825.99),
new Employee("李静", 18, 4502.99), new Employee("小三", 17, 1469.99), new Employee("小三", 17, 1469.99),
new Employee("小三", 17, 1469.99), new Employee("小三", 17, 1469.99));
/**
*
* 映射 map —— Lambda,将元素转换当作其它形式或提守信息,接收一个函数作为参数,改函数会被应用到每个元素上, 并将其映射当作一个新的元素。
* flatMap —— 接收一个函数作为参数,将流中的每个值都换当作另一个流,然后把所有的流连城一个流。
*/
@Test
public void test6() {
List<String> list = Arrays.asList("aaa", "bbb", "bbb", "ddd");
list.stream().map((str) -> str.toUpperCase()).forEach(System.out::println);
System.out.println("---------------------------");
employees.stream().map(Employee::getName).forEach(System.out::println);
System.out.println("---------------------------");
Stream<Stream<Character>> stream = list.stream().map(TestStreamAPI3::filterCharacter);
stream.forEach((sm) -> {
sm.forEach(System.out::println);
});
System.out.println("---------------------------");
Stream<Character> stream2 = list.stream().flatMap(TestStreamAPI3::filterCharacter);
stream2.forEach(System.out::println);
}
public static Stream<Character> filterCharacter(String str) {// add(Object obj) addAll(collection coll)
List<Character> list = new ArrayList<>();
for (Character character : str.toCharArray()) {
list.add(character);
}
return list.stream();
}
}
4、Stream排序
package com.stream.api4;
import java.util.Arrays;
import java.util.List;
import org.junit.Test;
import com.stream.api1.Employee;
public class TestStreamAPI4 {
List<Employee> employees = Arrays.asList(new Employee("张三", 12, 1200.99), new Employee("小明", 15, 4500.99),
new Employee("小丽", 16, 5500.99), new Employee("王二", 32, 1100.99), new Employee("二虎", 22, 9825.99),
new Employee("李静", 18, 4502.99), new Employee("小三", 17, 1469.99), new Employee("小三", 17, 1469.99),
new Employee("小三", 17, 1469.99), new Employee("小三", 17, 1469.99));
/**
* 排序 sorted() —— 天然排序(Comparable) sorted(Comparater com) —— 定制排序(Comparater)
*/
@Test
public void test1() {
List<String> list = Arrays.asList("ccc", "aaa", "bbb", "ddd", "eee");
list.stream().sorted().forEach(System.out::println);
System.out.println("--------------------------------------------");
employees.stream().sorted((e1, e2) -> {
if (e1.getAge() == e2.getAge()) {
return e1.getName().compareTo(e2.getName());
} else {
return Integer.compare(e1.getAge(), e2.getAge());
}
}).forEach(System.out::println);
}
}
5、Stream查找与匹配
package com.stream.api5;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import org.junit.Test;
import com.stream.api1.Employee;
import com.stream.api1.Employee.Status;
public class TestStreamAPI5 {
List<Employee> employees = Arrays.asList(new Employee("张三", 12, 1200.99, Status.BUSY),
new Employee("小明", 15, 4500.99, Status.BUSY), new Employee("小丽", 16, 5500.99, Status.BUSY),
new Employee("王二", 32, 1100.99, Status.FREE), new Employee("二虎", 22, 9825.99, Status.FREE),
new Employee("李静", 18, 4502.99, Status.FREE), new Employee("小三", 17, 1469.99, Status.VOCATION),
new Employee("小三", 17, 1469.99, Status.VOCATION), new Employee("小三", 17, 1469.99, Status.VOCATION),
new Employee("小三", 17, 1469.99, Status.VOCATION));
/**
* 查找与匹配 allMatch —— 查抄是否平匹配所有元素 anyMatch —— 查抄是否至少匹配一个元素 noneMatch ——
* 查抄是否没有匹配的元素 findFirst —— 返回第一个元素 findAny —— 返回当前流中的肆意元素 count —— 返回流中元素的总个数
* max —— 返回流中最大值 min —— 返回流中最小值
*/
@Test
public void test1() {
boolean b1 = employees.stream().allMatch(e -> e.getStatus().equals(Status.BUSY));
System.out.println(b1);
boolean b2 = employees.stream().anyMatch((e) -> e.getStatus().equals(Status.BUSY));
System.out.println(b2);
boolean b3 = employees.stream().noneMatch((e) -> e.getStatus().equals(Status.BUSY));
System.out.println(b3);
Optional<Employee> op1 = employees.stream().sorted((e1, e2) -> -Double.compare(e1.getSalary(), e2.getSalary()))
.findFirst();
System.out.println(op1.get());
Optional<Employee> op2 = employees.stream().filter((e) -> e.getStatus().equals(Status.FREE)).findAny();
System.out.println(op2.get());
Optional<Employee> op3 = employees.parallelStream().filter((e) -> e.getStatus().equals(Status.FREE)).findAny();
System.out.println(op3.get());
}
@Test
public void test2() {
Long count = employees.stream().count();
System.out.println(count);
Optional<Employee> op1 = employees.stream().max((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary()));
System.out.println(op1.get());
Optional<Double> op2 = employees.stream().map(Employee::getSalary).max(Double::compare);
System.out.println(op2.get());
}
}
6、Stream约与收集归
package com.stream.api6;
import java.util.Arrays;
import java.util.DoubleSummaryStatistics;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import org.junit.Test;
import com.stream.api1.Employee;
import com.stream.api1.Employee.Status;
public class TestStreamAPI6 {
List<Employee> employees = Arrays.asList(new Employee("张三", 12, 1200.99, Status.BUSY),
new Employee("小明", 15, 4500.99, Status.BUSY), new Employee("小丽", 16, 5500.99, Status.BUSY),
new Employee("王二", 32, 1100.99, Status.FREE), new Employee("二虎", 22, 9825.99, Status.FREE),
new Employee("李静", 18, 4502.99, Status.FREE), new Employee("小三", 17, 1469.99, Status.VOCATION),
new Employee("小三", 17, 1469.99, Status.VOCATION), new Employee("小三", 17, 1469.99, Status.VOCATION),
new Employee("小三", 17, 1469.99, Status.VOCATION));
/**
* 归约 reduce(T identity,BinaryOperator)/reduce(BinaryOperator) ——
* 可以将流中元素频频连系起来,获得一个值
*/
@Test
public void test1() {
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
Integer sum = list.stream().reduce(0, (x, y) -> x + y);
System.out.println(sum);
System.out.println("-------------------------------------------");
Optional<Double> op1 = employees.stream().map(Employee::getSalary).reduce(Double::sum);
System.out.println(op1.get());
}
/**
* 收集 collect —— 将流转换为其它形式,接收一个Collector接口的实现,用于给Stream中元素做汇总的方式
*/
@Test
public void test2() {
List<String> list = employees.stream().map(Employee::getName).collect(Collectors.toList());
list.forEach(System.out::println);
System.out.println("-----------------------");
Set<String> set = employees.stream().map(Employee::getName).collect(Collectors.toSet());
set.forEach(System.out::println);
System.out.println("-----------------------");
HashSet<String> hashSet = employees.stream().map(Employee::getName)
.collect(Collectors.toCollection(HashSet::new));
hashSet.forEach(System.out::println);
}
@Test
public void test3() {
// 总数
Long count = employees.stream().collect(Collectors.counting());
System.out.println(count);
System.out.println("-----------------------");
// 平均值
Double avg = employees.stream().collect(Collectors.averagingDouble(Employee::getSalary));
System.out.println(avg);
System.out.println("-----------------------");
// 总和
Double sum = employees.stream().collect(Collectors.summingDouble(Employee::getSalary));
System.out.println(sum);
System.out.println("-----------------------");
// 最大值
Optional<Employee> max = employees.stream()
.collect(Collectors.maxBy((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary())));
System.out.println(max.get());
System.out.println("-----------------------");
// 最大值
Optional<Employee> min = employees.stream()
.collect(Collectors.minBy((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary())));
System.out.println(min.get());
}
// 分组
@Test
public void test4() {
Map<Status, List<Employee>> map = employees.stream().collect(Collectors.groupingBy(Employee::getStatus));
System.out.println(map);
}
// 多级分组
@Test
public void test5() {
Map<Status, Map<String, List<Employee>>> map = employees.stream()
.collect(Collectors.groupingBy(Employee::getStatus, Collectors.groupingBy((e) -> {
if (e.getAge() < 16) {
return "青年";
} else if (e.getAge() < 18) {
return "中年";
} else {
return "老年";
}
})));
System.out.println(map);
}
// 分区
@Test
public void test6() {
Map<Boolean, List<Employee>> map = employees.stream()
.collect(Collectors.partitioningBy(e -> e.getSalary() > 5000));
System.out.println(map);
}
@Test
public void test7() {
DoubleSummaryStatistics collect = employees.stream().collect(Collectors.summarizingDouble(Employee::getSalary));
System.out.println(collect.getAverage());
System.out.println(collect.getCount());
System.out.println(collect.getMax());
System.out.println(collect.getMin());
System.out.println(collect.getSum());
}
@Test
public void test8() {
String str1 = employees.stream().map(Employee::getName).collect(Collectors.joining());
System.out.println(str1);
System.out.println("---------------------------------");
String str2 = employees.stream().map(Employee::getName).collect(Collectors.joining(","));
System.out.println(str2);
System.out.println("---------------------------------");
String str3 = employees.stream().map(Employee::getName).collect(Collectors.joining(",", "===", "==="));
System.out.println(str3);
}
}
7、Stream约操练
0 篇文章
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!