JAVA_Stream_练习
package airycode_java8.nice7; import airycode_java8.nice1.Employee;
import org.junit.Test; import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors; /**
* Created by admin on 2019/1/3.
*/
public class TestStramAPI { /***
* 1.给定一个数字列表,如何返回一个由每一个数字的平方构成的列表,给定【1,2,3,4,5】返回[1,4,9,16,25]
*/
@Test
public void test1(){
List<Integer> list = Arrays.asList(1,2,3,4,5);
List<Integer> collect = list.stream().map((x) -> x * x).collect(Collectors.toList());
collect.forEach(System.out::println);
} /***
* 2.用map和reduce方法数数流中有多少个emplloyee
*
*/
//准备数据
static List<Employee> employeeList = Arrays.asList(
new Employee("张三",18,9999.99, Employee.Status.FREE),
new Employee("李四",38,5555.55,Employee.Status.BUSY),
new Employee("王五",50,6666.66,Employee.Status.VOCATION),
new Employee("赵六",16,3333.33,Employee.Status.FREE),
new Employee("田七",8,7777.77,Employee.Status.BUSY) );
@Test
public void test2(){
Optional<Integer> sum = employeeList.stream().map((e) -> 1).reduce(Integer::sum);
System.out.println(sum.get());
} }
交易员和交易练习:
package airycode_java8.nice7; /**
* 交易员对象
* Created by admin on 2019/1/3.
*/
public class Trader { private String name;
private String city; 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 airycode_java8.nice7; /**
* 交易对象
* Created by admin on 2019/1/3.
*/
public class Transaction { private Trader trader;
private int year;
private int value;
private String currency; public Transaction(Trader trader,int year,int value,String currency){
this.trader = trader;
this.year = year;
this.value = value;
this.currency = currency;
} public Trader getTrader(){
return trader;
}
public int getYear(){
return year;
}
public int getValue(){
return value;
}
public String getCurrency(){
return currency;
} @Override
public String toString(){
return "i am transaction : my trader is : "
+ trader.getName()
+ " ; my year is : "
+ year
+ " ; my value is : "
+ value
+ " ; my currency is : "
+ currency;
}
} package airycode_java8.nice7; import org.junit.Before;
import org.junit.Test; import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors; import static java.util.Comparator.comparingInt;
import static java.util.stream.Collectors.*;
/**
* Created by admin on 2019/1/3.
*/
public class TraderExercise { List<Trader> traders = new LinkedList<>();
List<Transaction> transactions = new LinkedList<>(); @Before
public void init(){ Trader t1 = new Trader("trader1","剑桥");
Trader t2 = new Trader("trader2","米兰");
Trader t3 = new Trader("trader3","剑桥");
Trader t4 = new Trader("trader4","剑桥");
traders.addAll(Arrays.asList(t1,t2,t3,t4)); Transaction tran1 = new Transaction(t4,2011,300,"$");
Transaction tran2 = new Transaction(t1,2012,1000,"$");
Transaction tran3 = new Transaction(t1,2011,400,"¥");
Transaction tran4 = new Transaction(t2,2012,710,"¥");
Transaction tran5 = new Transaction(t2,2012,700,"$");
Transaction tran6 = new Transaction(t3,2012,950,"¥");
transactions.addAll(Arrays.asList(tran1,tran2,tran3,tran4,tran5,tran6));
} /***
* 1.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);
} /***
*2.交易员都在哪些不同的城市生活
*/
@Test
public void test2(){ traders.stream()
.map(Trader::getCity)
.distinct()
.forEach(System.out::println); } /***
*3.查找所有来自剑桥的交易员,并按姓名排序
*/
@Test
public void test3(){ // traders.stream()
// .filter((t)->"剑桥".equals(t.getCity()))
// .sorted((e1,e2)->e1.getName().compareTo(e2.getName()))
// .forEach(System.out::println);
traders.stream()
.filter((t)->"剑桥".equals(t.getCity()))
.sorted(Comparator.comparing(Trader::getName))
.forEach(System.out::println); } /***
*4.查询所有交易员的姓名字符串,并按字母排序
*/
@Test
public void test4(){ traders.stream()
.filter((t)->"剑桥".equals(t.getCity()))
.sorted(Comparator.comparing(Trader::getName))
.forEach(System.out::println); } /***
*5.有没有交易员在米兰
*/
@Test
public void test5(){ boolean any = traders.stream()
.filter((t) -> "米兰".equals(t.getCity()))
.findAny()
.isPresent();
System.out.println(any); } /***
* 6.打印在剑桥生活的交易员的所有交易金额
*/
@Test
public void test6(){ Integer sum = transactions.stream()
.filter(tran -> "剑桥".equals(tran.getTrader().getCity()))
.map(Transaction::getValue)
.reduce(0, (val1, val2) -> val1 + val2);
System.out.println(sum); } /***
* 7.所有交易中,最高的交易额是多少
*/
@Test
public void test7(){
transactions.stream()
.sorted(Comparator.comparing(Transaction::getValue).reversed())
.findFirst()
.ifPresent(System.out::println); transactions.stream()
.map(Transaction::getValue)
.reduce(Integer::max)
.ifPresent(System.out::println);
} /***
* 8.找到交易额中最小的金额
*/
@Test
public void test8(){
transactions.stream()
.map(Transaction::getValue)
.reduce(Integer::min)
.ifPresent(System.out::println); transactions.stream()
.min(Comparator.comparing(Transaction::getValue))
.ifPresent(System.out::println); transactions.stream()
.min(Comparator.comparing((Transaction t1) -> t1.getValue()))
.ifPresent(System.out :: println); } /***
* 9.统计每个交易员的记录
*/
@Test
public void test9(){
transactions.stream()
.collect(groupingBy(Transaction::getTrader))
.entrySet().stream()
.forEach(System.out::println); } /***
* 10.找到单笔交易最高的交易员
*/
@Test
public void test10(){
transactions.stream()
.max(Comparator.comparing(Transaction::getValue))
.ifPresent(tran->{
System.out.println(tran.getTrader());
});
} /***
* 11.统计交易总额最高的交易员(排序)
*/
@Test
public void test11(){
transactions.stream().collect(groupingBy(Transaction::getTrader))
.entrySet().stream().map(t->{
Map<String,Object> result = new HashMap<>();
int sum = t.getValue().stream().mapToInt(Transaction :: getValue).sum();
result.put("sum",sum);
result.put("trader",t.getKey());
return result; }).sorted(comparingInt((Map m) -> (int)m.get("sum")).reversed()).findFirst().ifPresent(System.out::println);
} /***
* 12.使用方法引用对transaction排序
*/
@Test
public void test12(){
transactions.stream().sorted(Comparator.comparing(Transaction::getValue)).forEach(System.out::println); System.out.println("--------------------------------------------------------------------------------"); //声明接口的实现方式
Function<Transaction,Integer> function = Transaction :: getValue;
Transaction[] transactionsArray = new Transaction[transactions.size()];
Arrays.sort(transactions.toArray(transactionsArray),Comparator.comparing(function));
Arrays.asList(transactionsArray).stream().forEach(System.out :: println);
} /***
* 13.根据trader(对象)将transaction分组
*/
@Test
public void test13(){
transactions.stream()
.collect(groupingBy(Transaction :: getTrader))
.entrySet().stream()
.forEach(System.out :: println);
} //【14.根据货币(字符串)类型分组
@Test
public void exercise14(){
transactions.stream()
.collect(groupingBy(Transaction :: getCurrency))
.entrySet().stream()
.forEach(System.out :: println);
}
//【15.获取交易总金额
@Test
public void exercise15(){
int sum1 = transactions.stream().mapToInt(Transaction::getValue).sum();
System.out.println("通过map转换求和sum1 = " + sum1);
int sum2 = transactions.stream().collect(Collectors.summingInt(Transaction::getValue));
System.out.println("通过collect汇总求和sum2 = " + sum2);
//规约操作都需要使用map将对象映射为返回值的类型
int sum3 = transactions.stream().map(Transaction::getValue).reduce(0,(t1,t2) -> t1 + t2);
System.out.println("通过reduce规约求和sum3 = " + sum3);
}
//【16.二级分类,先按照交易员分类,然后交易金额大于800归为high,低于800归为low
@Test
public void exercise16(){
transactions.stream()
.collect(groupingBy(Transaction :: getTrader,groupingBy(t -> {
if(t.getValue()< 800 ){
return "low";
}else {
return "heigh";
}
})))
.entrySet().stream()
.forEach(System.out :: println);
}
//【17.获取每个交易员,交易最大的一笔
@Test
public void exercise17(){
transactions.stream()
.collect(groupingBy(Transaction::getTrader,maxBy(Comparator.comparingInt(Transaction::getValue))))
.entrySet().stream()
.distinct()
.sorted(Comparator.comparing((Map.Entry m) -> {
Trader t = (Trader) m.getKey();
return t.getName();
}))
.forEach(System.out :: println);
} }
JAVA_Stream_练习的更多相关文章
随机推荐
- angular ajax请求 结果显示显示两次的问题
angular 项目中,由于用到ajax 请求,结果显示如下情况 同样的接口,显示两次,其中第一次请求情况为 request method 显示为opttions 第二次的情况是 为啥会出现如此的情况 ...
- prometheus: celery, redis-export
https://github.com/nlighten/tomcat_exporter https://github.com/prometheus/jmx_exporter https://vexxh ...
- P3292 [SCOI2016]幸运数字 线性基
正解:线性基+倍增 解题报告: 先放下传送门QAQ 然后这题,其实没什么太大的技术含量,,,?就几个知识点套在一起,除了代码长以外没任何意义,主要因为想复习下线性基的题目所以还是写下,,, 随便写下思 ...
- fork多线程进程时的坑(转)
add : 在fork多线程的进程时,创建的子进程只包含一个线程,该线程是调用fork函数的那个线程的副本.在man fork中,有The child process is created with ...
- mysql大表更新sql的优化策略(转)
看了该文章之后,很受启发,mysql在update时,一般也是先select.但注意,在Read Committed隔离级别下,如果没有使用索引,并不会锁住整个表, 还是只锁住满足查询条件的记录而已. ...
- nodejs 学习五 单元测试一
一. chai chai 自身是依赖nodejs的 assert,让检测更加语义化. chai 采用两种模式,TDD和BDD, TDD是类似自然语言方式 BDD是结构主义 chai文旦地址 二.moc ...
- C++的类大小
有以下C++类 #pragma pack(push) #pragma pack(1) class task /*:public OSThread*/{ //public: // void Entry( ...
- wc 统计命令
[root@localhost ~]# wc /etc/passwd // 统计行数.单词数.字符数 /etc/passwd [root@localhost ~]# wc -l /etc/passwd ...
- VMware Workstation 不可恢复错误 解决方法
问题: VMware Workstation 不可恢复错误: (vcpu-0) vcpu-0:VERIFY vmcore/vmm/main/cpuid.c:386 bugNr=1036521 日志文件 ...
- 20170731 培训Bootstrap
Bootstrap使用 涉及培训内容框架:--1 html html为标记语言,可以理解为容器,就是用来承载你想要展示到网页的内容的容器.版本也有很多,不同版本表示不同的标记的新增或者取代. Boot ...