Java8-Stream-Exercise

This article is used to record the comprehensive training of the previously learned Lambda and Stream

The value of the practice questions is still in the teaching video of Silicon Valley. Because Chinese is broad and profound, some questions have different understandings, and the results obtained are different. Just to achieve review and improve knowledge mastery, the code is directly below.

Bean first

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 + "]";
	}

}

Let's test the code again. The code uses filtering, sorting, reduction, grouping, averaging, maximum, minimum, minimum corresponding records, etc., and some implementations provide a variety of methods.

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());
	}
	
}

Once again, I sigh that Stream combined with Lambda is really awesome. The code that was released in the company before was JDK1.4 JDK1.6, which is really dirty (this is of course understandable, because the cost of replacing JDK is too high, no one pays)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324910033&siteId=291194637