【Way to java】Java8 新特性 2

Stream API

简介

Java8中有两大最为重要的改变。第一个是 Lambda 表达式;另外一
个则是 Stream API(java.util.stream.*)
Stream 是 Java8 中处理集合的关键抽象概念,它可以指定你希望对
集合进行的操作,可以执行非常复杂的查找、过滤和映射数据等操作。
使用Stream API 对集合数据进行操作,就类似于使用 SQL 执行的数
据库查询。也可以使用 Stream API 来并行执行操作。简而言之,
Stream API 提供了一种高效且易于使用的处理数据的方式

  1. Stream 自己不会存储元素
  2. Stream 不会改变源对象。相反,他们会返回一个持有结果的新Stream
  3. Stream 操作是延迟执行的。这意味着他们会等到需要结果的时候才执行

三个步骤

创建Stream

  1. 通过Collection系列集合提供的stream()或者parallelStream()
List<String> list = new ArrayList<>();
Stream<String> stream = list.stream();
  1. 通过Arrays中的静态方法stream()获取数组流
Employee[] emps = new Employee[10];
Stream<Employee> stream = Arrays.stream(emps);
  1. 通过Stream中的静态方法of()
Stream<String> stream = Stream.of("aa","bb","cc");
  1. 创建无限流
// 迭代
Stream<Integer> stream = Stream.iterate(0, (x)->x+2);
// 生成
Stream<Double> stream = Stream.generate(()->Math.random());

中间操作

多个中间操作可以连接起来形成一个流水线,除非流水线上触发终止操作,否则中间操作不会执行任何的处理!而在终止操作时一次性全部处理,称为“惰性求值”。

筛选与切片
// filter(Predicate p) 
// 接受Lambda,从流中排除某些元素
emps.stream()
	.filter((e) -> e.getAge() > 35);
	.forEach(System.out::println);
// distinct() 
// 筛选,通过流所生成元素的 hashCode() 和 equals() 去除重复元素,实体类要重写hashCode和equals方法
emps.stream()
	.distinct()
	.forEach(System.out::println);
// limit(long maxSize) 
// 截断流,使其元素不超过给定数量
emps.stream()
	.limit(2)
	.forEach(System.out::println);
// skip(long n) 
// 跳过元素返回一个扔掉了前 n 个元素的流。若流中元素不足 n 个,则返回一个空流。与 limit(n) 互补
emps.stream()
	.skip(2)
	.forEach(System.out::println);
映射
public static Stream<Character> filterCharacter(String str){
	List<Character> list = new ArrayList<>();
	for (Character ch : str.toCharArray()) {
		list.add(ch);
	}
	return list.stream();
}
// map(Function f) 
// 接收一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新的元素
Arrays.asList("aaa","bbb","ccc","ddd")
	.map((str)->str.toUpperCase())
	.foreach(System.out::println);
// mapToDouble(ToDoubleFunction f)
// 接收一个函数作为参数,该函数会被应用到每个元素上,产生一个新的 DoubleStream
Arrays.asList(new Double(3.3),new Double(4.4))
	.mapToDouble(Double::doubleValue)
	.foreach(System.out::println);
// mapToInt(ToIntFunction f)
// 接收一个函数作为参数,该函数会被应用到每个元素上,产生一个新的 IntStream
Arrays.asList(new Integer(1),new Integer(2))
	.mapToInt(Integer::intValue)
	.foreach(System.out::println);
// mapToLong(ToLongFunction f)
// 接收一个函数作为参数,该函数会被应用到每个元素上,产生一个新的 LongStream
Arrays.asList(new Long(3),new Double(4))
	.mapToLong(Long::longValue)
	.foreach(System.out::println);
// flatMap(Function f)
// 接收一个函数作为参数,将流中的每个值都换成另一个流,然后把所有流连接成一个流
Stream<Stream<Character>> stream2 = strList.stream()
			   .map(TestStreamAPI1::filterCharacter);
stream2.forEach((sm) -> {
			sm.forEach(System.out::println);
		});
		
Stream<Character> stream3 = strList.stream()
			   .flatMap(TestStreamAPI1::filterCharacter);
stream3.forEach(System.out::println);
排序
List<Employee> emps = Arrays.asList(
		new Employee(102, "李四", 59, 6666.66),
		new Employee(101, "张三", 18, 9999.99),
		new Employee(103, "王五", 28, 3333.33),
		new Employee(104, "赵六", 8, 7777.77),
		new Employee(104, "赵六", 8, 7777.77),
		new Employee(104, "赵六", 8, 7777.77),
		new Employee(105, "田七", 38, 5555.55)
);
// 自然排序
emps.stream()
	.map(Employee::getName)
	.sorted()
	.forEach(System.out::println);

// 定制排序
emps.stream()
	.sorted((x, y) -> {
		if(x.getAge() == y.getAge()){
			return x.getName().compareTo(y.getName());
		}else{
			return Integer.compare(x.getAge(), y.getAge());
		}
	}).forEach(System.out::println);

终止操作

查找与匹配
List<Employee> emps = Arrays.asList(
			new Employee(102, "李四", 59, 6666.66, Status.BUSY),
			new Employee(101, "张三", 18, 9999.99, Status.FREE),
			new Employee(103, "王五", 28, 3333.33, Status.VOCATION),
			new Employee(104, "赵六", 8, 7777.77, Status.BUSY),
			new Employee(104, "赵六", 8, 7777.77, Status.FREE),
			new Employee(104, "赵六", 8, 7777.77, Status.FREE),
			new Employee(105, "田七", 38, 5555.55, Status.BUSY)
	);
// allMatch(Predicate p)
// 检查是否匹配所有元素
boolean bl = emps.stream()
				.allMatch((e) -> e.getStatus().equals(Status.BUSY));
// anyMatch(Predicate p)
// 检查是否至少匹配一个元素
boolean bl1 = emps.stream()
				.anyMatch((e) -> e.getStatus().equals(Status.BUSY));
// noneMatch(Predicate p)
// 检查是否没有匹配所有元素
boolean bl2 = emps.stream()
				.noneMatch((e) -> e.getStatus().equals(Status.BUSY));
// findFirst()
// 返回第一个元素
Optional<Employee> op = emps.stream()
	.sorted((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary()))
	.findFirst();
// findAny()
// 返回当前流中的任意元素
Optional<Employee> op2 = emps.parallelStream()
			.filter((e) -> e.getStatus().equals(Status.FREE))
			.findAny();
// count()
// 返回流中元素总数
long count = emps.stream()
				 .filter((e) -> e.getStatus().equals(Status.FREE))
				 .count();
// max(Comparator c)
// 返回流中最大值
Optional<Double> op = emps.stream()
			.map(Employee::getSalary)
			.max(Double::compare);
// min(Comparator c)
// 返回流中最小值
Optional<Employee> op2 = emps.stream()
			.min((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary()));
// forEach(Consumer c)
// 内部迭代(使用 Collection 接口需要用户去做迭代,称为外部迭代。相反,Stream API 使用内部迭代——它帮你把迭代做了)
emps.stream()
	.map(Employee::getName)
	.sorted()
	.forEach(System.out::println);
归约
// reduce(T iden, BinaryOperator b)
// 可以将流中元素反复结合起来,得到一个值,返回 T
Integer sum = list.stream()
			.reduce(0, (x, y) -> x + y);
// reduce(BinaryOperator b)
// 可以将流中元素反复结合起来,得到一个值,返回 Optional<T>
Optional<Double> op = emps.stream()
			.map(Employee::getSalary)
			.reduce(Double::sum);
收集
// collect(Collector c)
// 将流转换为其他形式。接收一个 Collector接口的实现,用于给Stream中元素做汇总的方法
List<String> list = emps.stream()
			.map(Employee::getName)
			.collect(Collectors.toList());

Set<String> set = emps.stream()
			.map(Employee::getName)
			.collect(Collectors.toSet());

HashSet<String> hs = emps.stream()
			.map(Employee::getName)
			.collect(Collectors.toCollection(HashSet::new));

Optional<Double> max = emps.stream()
			.map(Employee::getSalary)
			.collect(Collectors.maxBy(Double::compare));

Optional<Employee> op = emps.stream()
			.collect(Collectors.minBy((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary())));

Double sum = emps.stream()
			.collect(Collectors.summingDouble(Employee::getSalary));


Double avg = emps.stream()
			.collect(Collectors.averagingDouble(Employee::getSalary));

Long count = emps.stream()
			.collect(Collectors.counting());

DoubleSummaryStatistics dss = emps.stream()
			.collect(Collectors.summarizingDouble(Employee::getSalary));

// 分组
Map<Status, List<Employee>> map = emps.stream()
	.collect(Collectors.groupingBy(Employee::getStatus));

// 多级分组
Map<Status, Map<String, List<Employee>>> map = emps.stream()
	.collect(Collectors.groupingBy(Employee::getStatus, Collectors.groupingBy((e) -> {
		if(e.getAge() >= 60)
			return "老年";
		else if(e.getAge() >= 35)
			return "中年";
		else
			return "成年";
	})));

// 分区,符合不符合区分开
Map<Boolean, List<Employee>> map = emps.stream()
	.collect(Collectors.partitioningBy((e) -> e.getSalary() >= 5000));

// 连接
String str = emps.stream()
			.map(Employee::getName)
			.collect(Collectors.joining("," , "----", "----"));

例题

  1. 给定一个数字列表,如何返回一个由每个数的平方构成的列表呢?给定【1,2,3,4,5】, 应该返回【1,4,9,16,25】
@Test
public void test(){
	Integer[] nums = new Integer[]{1,2,3,4,5};
	Arrays.stream(nums)
		  .map((x) -> x * x)
		  .forEach(System.out::println);
}
  1. 怎样用 map 和 reduce 方法数一数流中有多少个Employee?
List<Employee> emps = Arrays.asList(
	new Employee(102, "李四", 59, 6666.66, Status.BUSY),
		new Employee(101, "张三", 18, 9999.99, Status.FREE),
		new Employee(103, "王五", 28, 3333.33, Status.VOCATION),
		new Employee(104, "赵六", 8, 7777.77, Status.BUSY),
		new Employee(104, "赵六", 8, 7777.77, Status.FREE),
		new Employee(104, "赵六", 8, 7777.77, Status.FREE),
		new Employee(105, "田七", 38, 5555.55, Status.BUSY)
);
@Test
public void test(){
	Optional<Integer> count = emps.stream()
		.map((e) -> 1)
		.reduce(Integer::sum);
	System.out.println(count.get());
}
  1. 找出2011年发生的所有交易, 并按交易额排序(从低到高)
  2. 交易员都在哪些不同的城市工作过?
  3. 查找所有来自剑桥的交易员,并按姓名排序
  4. 返回所有交易员的姓名字符串,按字母顺序排序
  5. 有没有交易员是在米兰工作的?
  6. 打印生活在剑桥的交易员的所有交易额
  7. 所有交易中,最高的交易额是多少
  8. 找到交易额最小的交易
List<Transaction> transactions = null;
@Before
public void before(){
	Trader raoul = new Trader("Raoul", "Cambridge");
	Trader mario = new Trader("Mario", "Milan");
	Trader alan = new Trader("Alan", "Cambridge");
	Trader brian = new Trader("Brian", "Cambridge");
	
	transactions = Arrays.asList(
			new Transaction(brian, 2011, 300),
			new Transaction(raoul, 2012, 1000),
			new Transaction(raoul, 2011, 400),
			new Transaction(mario, 2012, 710),
			new Transaction(mario, 2012, 700),
			new Transaction(alan, 2012, 950)
	);
}
// 找出2011年发生的所有交易, 并按交易额排序(从低到高)
@Test
public void test1(){
	transactions.stream()
				.filter((t) -> t.getYear() == 2011)
				.sorted((t1, t2) -> Integer.compare(t1.getValue(), t2.getValue()))
				.forEach(System.out::println);
	}
// 交易员都在哪些不同的城市工作过?
@Test
public void test2(){
	transactions.stream()
				.map((t) -> t.getTrader().getCity())
				.distinct()
				.forEach(System.out::println);
}
// 查找所有来自剑桥的交易员,并按姓名排序
@Test
public void test3(){
	transactions.stream()
				.filter((t) -> t.getTrader().getCity().equals("Cambridge"))
				.map(Transaction::getTrader)
				.sorted((t1, t2) -> t1.getName().compareTo(t2.getName()))
				.distinct()
				.forEach(System.out::println);
}
// 返回所有交易员的姓名字符串,按字母顺序排序
@Test
public void test4(){
	transactions.stream()
				.map((t) -> t.getTrader().getName())
				.sorted()
				.forEach(System.out::println);
	System.out.println("-----------------------------------");
	String str = transactions.stream()
				.map((t) -> t.getTrader().getName())
				.sorted()
				.reduce("", String::concat);
	System.out.println(str);
	System.out.println("------------------------------------");
	transactions.stream()
				.map((t) -> t.getTrader().getName())
				.flatMap(TestTransaction::filterCharacter)
				.sorted((s1, s2) -> s1.compareToIgnoreCase(s2))
				.forEach(System.out::print);
}
public static Stream<String> filterCharacter(String str){
	List<String> list = new ArrayList<>();
	for (Character ch : str.toCharArray()) {
		list.add(ch.toString());
	}
	return list.stream();
}
// 有没有交易员是在米兰工作的?
@Test
public void test5(){
	boolean bl = transactions.stream()
				.anyMatch((t) -> t.getTrader().getCity().equals("Milan"));
	
	System.out.println(bl);
}
// 打印生活在剑桥的交易员的所有交易额
@Test
public void test6(){
	Optional<Integer> sum = transactions.stream()
				.filter((e) -> e.getTrader().getCity().equals("Cambridge"))
				.map(Transaction::getValue)
				.reduce(Integer::sum);
	
	System.out.println(sum.get());
}
// 所有交易中,最高的交易额是多少
@Test
public void test7(){
	Optional<Integer> max = transactions.stream()
				.map((t) -> t.getValue())
				.max(Integer::compare);
	
	System.out.println(max.get());
}
// 找到交易额最小的交易
@Test
public void test8(){
	Optional<Transaction> op = transactions.stream()
				.min((t1, t2) -> Integer.compare(t1.getValue(), t2.getValue()));
	
	System.out.println(op.get());
}

接口中的默认方法和静态方法

新时间日期API

其他新特性

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值