Java8-Stream-练习

这一篇用来记录对前面学习的Lambda和Stream的综合训练

练习题取值尚硅谷教学视频,因为中文的博大精深,有一些题理解不一样,求出来的结果也不一样,只求达到复习和提高知识掌握度,下面直接上代码

先来Bean

package com.jv.java8.stream;
//交易员
public class Trader {

	private String name;
	private String city;

	public Trader() {
	}

	public Trader(String name, String city) {
		this.name = name;
		this.city = city;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getCity() {
		return city;
	}

	public void setCity(String city) {
		this.city = city;
	}

	@Override
	public String toString() {
		return "Trader [name=" + name + ", city=" + city + "]";
	}

}
package com.jv.java8.stream;
//交易
public class Transaction {

	//交易员
	private Trader trader;
	//交易日期
	private int year;
	//交易金额
	private int value;

	public Transaction() {
	}

	public Transaction(Trader trader, int year, int value) {
		this.trader = trader;
		this.year = year;
		this.value = value;
	}

	public Trader getTrader() {
		return trader;
	}

	public void setTrader(Trader trader) {
		this.trader = trader;
	}

	public int getYear() {
		return year;
	}

	public void setYear(int year) {
		this.year = year;
	}

	public int getValue() {
		return value;
	}

	public void setValue(int value) {
		this.value = value;
	}

	@Override
	public String toString() {
		return "Transaction [trader=" + trader + ", year=" + year + ", value="
				+ value + "]";
	}

}

再来测试代码,代码中使用到了过滤,排序,归约,分组,求平均值,最大值,最小值,最小值对应记录等等,而且有的实现提供了多种方式。

package com.jv.java8.stream;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import org.junit.Before;
import org.junit.Test;

import com.jv.bean.Cust;

/*
 * Stream API练习
 */
public class StreamPractice {
	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)
		);
	}
	
	List<Cust> custs = Arrays.asList(
			new Cust(101,"梅西",30,33000000L),
			new Cust(102,"伊布",35,23000000L),
			new Cust(103,"哈维",34,20000000L),
			new Cust(104,"伊列斯塔",33,18000000L),
			new Cust(105,"小罗",37,15000000L),
			new Cust(106,"内马尔",27,32000000L),
			new Cust(106,"内马尔",27,32000000L),
			new Cust(106,"姆巴佩",23,30500000L)
			);
	
	@Test
	public void test0() {
		/*
		 * 给定一个数字列表,返回每个数字平反的列表
		 */
		List<Integer> l1 = Arrays.asList(1,2,3,4).stream().map(x->x*x).collect(Collectors.toList());
		System.out.println(l1);
		System.out.println("##########################");
		/*
		 * 用Map和Reduce计算流中有多少个Cust对象
		 * 当然你可以有很多种方法都可以统计列表中对象的个数,只是为了更进一步了解Stream API的用法,才要求这样做
		 */
		Integer ic1 = custs.stream().map(Cust::getAge).reduce(0, (x,y)->x+1);
		System.out.println(ic1);
		Integer ic2 = custs.stream().map(e -> 1).reduce(0, Integer::sum);
		System.out.println(ic2);
		
	}
	
	
	//1. 找出2011年发生的所有交易, 并按交易额排序(从低到高)
	@Test
	public void test1() {
		transactions.stream().filter(x->x.getYear()==2011).sorted((x,y)->{
			if(x.getValue()>y.getValue()) {
				return 1;
			}else if(x.getValue()<y.getValue()) {
				return -1;
			}else {
				return 0;
			}
			
		}).forEach(System.out::println);
	}
	
	
	//2. 交易员都在哪些不同的城市工作过?
	@Test
	public void test2() {
		//实际上就是找出所有交易员工作的城市并排重
		//方式1
		transactions.stream().map(Transaction::getTrader).map(Trader::getCity).distinct().forEach(System.out::println);
		//方式2
		transactions.stream().map(x->x.getTrader().getCity()).distinct().forEach(System.out::println);
	}
	
	
	//3. 查找所有来自剑桥的交易员,并按姓名排序
	@Test
	public void test3() {
		transactions.stream().filter(x->x.getTrader().getCity().equals("Cambridge")).sorted((x,y)->{
			return x.getTrader().getName().compareTo(y.getTrader().getName());
		}).forEach(System.out::println);
	}
	
	//4. 返回所有交易员的姓名字符串,按字母顺序排序
	@Test
	public void test4() {
		//方式1
		String s = transactions.stream().map(x->x.getTrader().getName()).distinct().sorted().collect(Collectors.joining(","));
		System.out.println(s);
		//方式2
		String s1 = transactions.stream().map(x->x.getTrader().getName()).distinct().sorted().reduce("", (x,y)->x+","+y).replaceFirst(",", "");
		System.out.println(s1);
	}
	
	//5. 有没有交易员是在米兰工作的?
	@Test
	public void test5() {
		Boolean b = transactions.stream().anyMatch(x->x.getTrader().getCity().equals("Milan"));
		System.out.println(b);
	}
	
	
	//6. 打印生活在剑桥的交易员的所有交易额
	@Test
	public void test6() {
		//方式1
		Map<Object, List<Transaction>> mt = transactions.stream().filter(x->x.getTrader().getCity().equals("Cambridge"))
							 .collect(Collectors.groupingBy(x->x.getTrader().getName()));
		//System.out.println(mt);
		for(Object obj:mt.keySet()) {
			Integer i = mt.get(obj.toString()).stream().collect(Collectors.summingInt(x->x.getValue()));
			System.out.println(obj+":"+i);
		}
		
		//方式2
		Map<Object,Integer> mt1 = transactions.stream().filter(x->x.getTrader().getCity().equals("Cambridge"))
							 .collect(Collectors.groupingBy(x->x.getTrader().getName(), Collectors.summingInt(x->x.getValue())));
		System.out.println(mt1);
		
		//很明显流提供的支持确实很强大,第二种方式要简单好多好多
	}
	
	
	//7. 所有交易中,最高的交易额是多少
	@Test
	public void test7() {
		Optional<Integer> i = transactions.stream().map(Transaction::getValue).collect(Collectors.maxBy(Integer::compare));
		System.out.println(i.get());
	}
	
	//8. 找到交易额最小的交易
	@Test
	public void test8() {
		Optional<Transaction> op = transactions.stream().min((x,y)->Integer.compare(x.getValue(), y.getValue()));
		System.out.println(op.get());
	}
	
}

再次感叹Stream结合Lambda确实很牛啊。以前在公司解除的代码都是JDK1.4 JDK1.6的,真是土到渣了(这当然是可以理解的,因为换JDK成本太高,没人买单)

转载于:https://my.oschina.net/u/3049601/blog/1624066

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值