排序:
@Test
public void sort() throws Exception{
list.stream().sorted((x,y)->{
if(x.getAge().compareTo(y.getAge())==0){
return x.getName().compareTo(y.getName());
}else {
return y.getAge().compareTo(x.getAge());
}
}).forEach(System.out::println);
}
线程池:
@Test
public void threadpool() throws Exception{
ExecutorService e = new ThreadPoolExecutor(1,2,10,TimeUnit.MINUTES,
new ArrayBlockingQueue<>(1), Executors.defaultThreadFactory(),new ThreadPoolExecutor.DiscardPolicy());
Callable<Integer> callable = ()->{
IntSummaryStatistics collect = list.stream().map(UserPo::getAge).collect(Collectors.summarizingInt(x -> x));
Long sum = collect.getSum();
return sum.intValue();
};
Future<Integer> submit = e.submit(callable);
System.err.println(submit.get());
}
Steam流创建
@Test
public void test1(){
//通过 Arrays 中的 stream() 获取一个数组流
Integer[] nums = new Integer[10];
Stream<Integer> stream1 = Arrays.stream(nums);
//通过 Stream 类中静态方法 of()
Stream<Integer> stream2 = Stream.of(1,2,3,4,5,6);
Optional<Integer> reduce = stream2.reduce(Integer::sum);
//创建无限流
//迭代
Stream<Integer> stream3 = Stream.iterate(0, (x) -> x + 2).limit(10);
stream3.forEach(System.out::println);
//生成
Stream<Double> stream4 = Stream.generate(Math::random).limit(2);
stream4.forEach(System.out::println);
}
LocalDate:
@Test
public void test7(){
//获取中国当前时间
LocalDateTime ldt = LocalDateTime.now(ZoneId.of("Asia/Shanghai"));
System.out.println(ldt);
//获取美国当前时间
ZonedDateTime zdt = ZonedDateTime.now(ZoneId.of("US/Pacific"));
System.out.println(zdt);
}
// DateTimeFormatter : 解析和格式化日期或时间
@Test
public void test5(){
//localdate转字符串
DateTimeFormatter yyyyMMdd = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String format = ldt.format(yyyyMMdd);
System.out.println(format);
LocalDateTime parse = ldt.parse(format,yyyyMMdd);
System.out.println(parse);
}
//TemporalAdjuster : 时间校正器
@Test
public void test4(){
LocalDateTime ldt = LocalDateTime.now();
LocalDateTime ldt2 = ldt.withDayOfMonth(10);
LocalDateTime ldt3 = ldt.with(TemporalAdjusters.next(DayOfWeek.SUNDAY));
//自定义:下一个工作日
LocalDateTime ldt5 = ldt.with((l) -> {
LocalDateTime ldt4 = (LocalDateTime) l;
DayOfWeek dow = ldt4.getDayOfWeek();
if(dow.equals(DayOfWeek.FRIDAY)){
return ldt4.plusDays(3);
}else if(dow.equals(DayOfWeek.SATURDAY)){
return ldt4.plusDays(2);
}else{
return ldt4.plusDays(1);
}
});
}
//Duration : 用于计算两个“时间”间隔
//Period : 用于计算两个“日期”间隔
@Test
public void test3(){
Instant ins1 = Instant.now();
System.out.println("--------------------");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
Instant ins2 = Instant.now();
System.out.println("所耗费时间为:" + Duration.between(ins1, ins2));
System.out.println("----------------------------------");
LocalDate ld1 = LocalDate.now();
LocalDate ld2 = LocalDate.of(2011, 1, 1);
Period pe = Period.between(ld2, ld1);
System.out.println(pe.getYears());
System.out.println(pe.getMonths());
System.out.println(pe.getDays());
}
题目联系:
static List<UserPo> list=LambdaUtils.list;
/*
1. 给定一个数字列表,如何返回一个由每个数的平方构成的列表呢?
,给定【1,2,3,4,5】, 应该返回【1,4,9,16,25】。
*/
@Test
public void answer1(){
Integer[] nums = new Integer[]{1,2,3,4,5};
List<Integer> collect = Arrays.asList(nums).stream().map(x -> x * x).collect(Collectors.toList());
System.out.println(collect);
Integer reduce = Arrays.asList(nums).stream().map(x -> x * x).reduce(0, Integer::sum);
System.out.println(reduce);
}
/*
2. 怎样用 map 和 reduce 方法数一数流中有多少个user呢?
*/
@Test
public void answer2(){
System.out.println(list.stream().count());
Integer integer = list.stream().map(x -> 1).reduce((x, y) -> x + y).get();
Integer integer1 = list.stream().map(x -> 1).reduce(Integer::sum).get();
System.out.println("integer:"+integer);
System.out.println("integer1:"+integer1);
}
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)
);
}
//1. 找出2011年发生的所有交易, 并按交易额排序(从低到高)
@Test
public void answer3(){
transactions.stream().filter(x -> x.getYear() == 2011).sorted(Comparator.comparingDouble(Transaction::getValue)).forEach(
y-> System.out.println(y)
);
System.out.println("-----------------------------------------------------------");
transactions.stream().filter(x -> x.getYear() == 2011).sorted(Comparator.comparingDouble((x) -> x.getValue())).forEach(
y -> System.out.println(y)
);
System.out.println("-----------------------------------------------------------");
transactions.stream().filter(x -> x.getYear() == 2011).sorted((x,y)->Integer.compare(x.getValue(),y.getValue())).forEach(
y-> System.out.println(y)
);
}
//2. 交易员都在哪些不同的城市工作过?
@Test
public void answer4(){
transactions.stream().map(o->o.getTrader().getCity()).distinct().forEach(o-> System.out.println(o));
}
//3. 查找所有来自剑桥的交易员,并按姓名排序
@Test
public void answer5(){
transactions.stream().filter(o->o.getTrader().getCity().equalsIgnoreCase("Cambridge"))
.map(o->o.getTrader())
.sorted((x,y)->x.getName().compareTo(y.getName())).distinct()
.forEach(o-> System.out.println(o));
}
//4. 返回所有交易员的姓名字符串,按字母顺序排序
@Test
public void answer6(){
String collect = transactions.stream().map(o -> o.getTrader().getName()).sorted((x, y) -> x.compareTo(y)).collect(Collectors.joining("-"));
System.out.println("collect:"+collect);
String collect1 = transactions.stream().map(o -> o.getTrader().getName())
.flatMap(x->{
List<String> str = new LinkedList<>();
char[] chars = x.toCharArray();
for (char aChar : chars) {
str.add(String.valueOf(aChar));
}
return str.stream();
}).sorted((x, y) -> x.compareToIgnoreCase(y)).reduce("",String::concat);
System.out.println("collect1:"+collect1);
}
//5. 有没有交易员是在米兰工作的?
@Test
public void answer7(){
boolean milan = transactions.stream().anyMatch(o -> o.getTrader().getCity().equals("Milan"));
System.out.println(milan);
}
//6. 打印生活在剑桥的交易员的所有交易额
@Test
public void answer8(){
transactions.stream().filter(o -> o.getTrader().getCity().equals("Milan")).forEach(o->{
System.out.println(o.getValue());
});
System.out.println("-----------------------------");
Integer milan = transactions.stream().filter(o -> o.getTrader().getCity().equals("Milan"))
.map(o -> o.getValue()).reduce(0, (x, y) -> x + y);
System.out.println("milan:"+milan);
Integer milan1 = transactions.stream().filter(o -> o.getTrader().getCity().equals("Milan"))
.map(o -> o.getValue()).reduce(0, Integer::sum);
System.out.println("milan1:"+milan1);
}
//7. 所有交易中,最高的交易额是多少
@Test
public void answer9(){
Optional<Integer> max = transactions
.stream()
.map(Transaction::getValue)
.max(Integer::compareTo);
System.out.println(max.get());
}
//8. 找到交易额最小的交易
@Test
public void answer10(){
Optional<Integer> collect = transactions.stream().map(Transaction::getValue)
.collect(Collectors.minBy(Integer::compare));
System.out.println(collect.get());
}
@Test
public void reduce(){
DoubleSummaryStatistics dss = list.stream()
.collect(Collectors.summarizingDouble(UserPo::getAge));
dss.getSum();
dss.getAverage();
dss.getCount();
dss.getMax();
dss.getMin();
HashSet<String> hs = list.stream()
.map(UserPo::getName)
.collect(Collectors.toCollection(HashSet::new));
}
//多级分组
@Test
public void test6(){
Map<UserPo.Status, Map<String, List<UserPo>>> map = list.stream()
.collect(Collectors.groupingBy(UserPo::getStatus, Collectors.groupingBy((e) -> {
if(e.getAge() >= 60)
return "老年";
else if(e.getAge() >= 35)
return "中年";
else
return "成年";
})));
System.out.println(map);
}
//分区
@Test
public void test7(){
Map<Boolean, List<UserPo>> map = list.stream()
.collect(Collectors.partitioningBy((e) -> e.getAge() >= 24));
System.out.println(map);
}
//字符拼接
@Test
public void test8(){
String str = list.stream()
.map(UserPo::getName)
.collect(Collectors.joining("," , "----", "----"));
System.out.println(str);
}
//Collectors 规约计算
@Test
public void test9(){
Optional<Integer> sum = list.stream()
.map(UserPo::getAge)
.collect(Collectors.reducing(Integer::sum));
System.out.println(sum.get());
}