lambdaExpression
package com.fcc.lambda;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
/**
* @description
* @auther feicongcong
* @date 2019/10/30
*/
public class LambdaExpression {
//lambda 语法
//在哪里如何使用lambda
//excute around parttern
//functional interfaces
//method references
//type interfaces
//composing lambdas
public static void main(String[] args){
Comparator<Apple> byColor =new Comparator<Apple>() {
@Override
public int compare(Apple o1, Apple o2) {
return o1.getColor().compareTo(o2.getColor());
}
};
List<Apple> list= Collections.emptyList();
list.sort(byColor);
Comparator<Apple> byColor2= (o1, o2) -> {
return o1.getColor().compareTo(o2.getColor());
};
Comparator<Apple> byColor3= (o1, o2) -> o1.getColor().compareTo(o2.getColor());
//parameter list arrow lambda body
//(o1, o2) -> o1.getColor().compareTo(o2.getColor());
//合法lambda
Consumer<Apple> consumer=(Apple a)-> System.out.println(a);
Function<String,Integer> function=(String s)->s.length();
Predicate<Apple> p = (Apple a)->a.getColor().equals("green");
Function<Apple,Boolean> function1=(Apple a)->a.getColor().equals("green");
Supplier<Apple> appleSupplier=Apple::new;
// (int x,int y)->{
// System.out.println(x);
// System.out.println(y);
// };
//
// ()->42;
//(parameters)->expression
//(parameters)->{statements;}
//@FunctionInterface 只有一个抽象方法
}
public interface Test{
public int fun();
}
}
lambdaUsage
package com.fcc.lambda;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.*;
/**
* @description
* @auther feicongcong
* @date 2019/11/7
*/
public class LambdaUsage {
//Predicate boolean test(T t)
//Consumer void accept(T t)
//Function<T,R> R apply(T t)
//Supplier<T> T get()
@FunctionalInterface
public interface Adder{
int add(int a ,int b);
}
@FunctionalInterface
public interface empity extends Adder{
}
private static List<Apple> filter(List<Apple> source, Predicate<Apple> predicate){
List<Apple> result = new ArrayList<>();
for(Apple a : source){
if(predicate.test(a)){
result.add(a);
}
}
return result;
}
private static List<Apple> filterByWeight(List<Apple> source , LongPredicate predicate){
List<Apple> result =new ArrayList<>();
for(Apple a:source){
if(predicate.test(a.getWeight())){
result.add(a);
}
}
return result;
}
private static List<Apple> filterByBipredicate(List<Apple> source , BiPredicate<String,Long> predicate){
List<Apple> result =new ArrayList<>();
for(Apple a:source){
if(predicate.test(a.getColor(),a.getWeight())){
result.add(a);
}
}
return result;
}
private static void simpleTestConsumer(List<Apple> source , Consumer<Apple> consumer){
for(Apple a:source){
consumer.accept(a);
}
}
private static void simpleBiConsumer(String c,List<Apple> source , BiConsumer<Apple,String> consumer){
for(Apple a:source){
consumer.accept(a,c);
}
}
private static String testFunction(Apple apple,Function<Apple,String> fun){
return fun.apply(apple);
}
private static Apple testBiFunction(String color,long weight,BiFunction<String,Long,Apple> fun){
return fun.apply(color,weight);
}
public static void main(String[] args){
// Runnable r=()-> System.out.println("Hello");
// Runnable r2=new Runnable(){
// @Override
// public void run() {
// System.out.println("hello");
// }
// };
// process(r);
// process(r2);
// process(()-> System.out.println(""));
List<Apple> list= Arrays.asList(new Apple("green",150),new Apple("red",150));
System.out.println(filter(list,apple->apple.getColor().equals("green")));
System.out.println(filterByWeight(list,a->a>100));
System.out.println(filterByBipredicate(list,(c,w)->c.equals("green")&&w>100L));
System.out.println("=========");
simpleTestConsumer(list,a-> System.out.println(a));
simpleBiConsumer("xxx",list,(a,c)-> System.out.println(c+a.getColor()+":weight=>"+a.getWeight()));
System.out.println(testFunction(new Apple("yellow",100L),a->a.toString()));
IntFunction<Double> f=i->i*100.0D;
System.out.println(f.apply(10));
System.out.println(testBiFunction("blue",130,(c,w)->new Apple(c,w)));
Supplier<String> s= String::new;
System.out.println(s.get().getClass());
System.out.println(createApple(()->new Apple("green",100)));
final int i=0;
new Runnable(){
@Override
public void run() {
// i++;
System.out.println(i);
}
};
Runnable r=()-> System.out.println(i);
// i++;
}
public static void process(Runnable r){
r.run();
}
private static Apple createApple(Supplier<Apple> supplier){
return supplier.get();
}
}
LocalDate
package com.fcc.lambda.date;
import org.springframework.cglib.core.Local;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoField;
import java.util.Calendar;
import java.util.Date;
/**
* @description
* @auther feicongcong
* @date 2019/11/7
*/
public class DateTest {
public static void main(String[] args){
//LocalDate
//LocalTime
//LocalDateTime
//Instant 时刻/瞬间
/*
Date date= new Date(116,2,18);
System.out.println(date);
//输出时间看起来不准 Fri Mar 18 00:00:00 CST 2016
SimpleDateFormat sdf= new SimpleDateFormat("yyyyMMdd");
//多线程不安全,需加锁处理
for(int i=0;i<30;i++){
new Thread(()->{
Date parseDate=null;
for(int x=0;x<100;x++){
try {
parseDate=sdf.parse("20160505");
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println(parseDate);
}
}).start();
}
*/
// testLocalDate();
// testLocalTime();
// testLocalDateAndTime();
// try{
// testInstant();
//
// }catch (Exception e){
// e.printStackTrace();
// }
// testDuration();
// testPeriod();
// testDateFormat();
testDateParse();
}
private static void testLocalDate(){
//现场安全
LocalDate localDate= LocalDate.of(2016,11,13);
System.out.println(localDate);
System.out.println(localDate.getYear());
System.out.println(localDate.getMonth());
System.out.println(localDate.getMonthValue());
System.out.println(localDate.getDayOfYear());
System.out.println(localDate.getDayOfMonth());
System.out.println(localDate.getDayOfWeek());
System.out.println(LocalDate.now());
System.out.println(localDate.get(ChronoField.DAY_OF_MONTH));
}
private static void testLocalTime(){
LocalTime.of(12,12,12);
LocalTime time= LocalTime.now();
System.out.println(time);
System.out.println(time.getHour());
System.out.println(time.getMinute());
System.out.println(time.getSecond());
}
private static void testLocalDateAndTime(){
LocalDate localDate=LocalDate.now();
LocalTime localTime=LocalTime.now();
LocalDateTime localDateTime=LocalDateTime.of(localDate,localTime);
System.out.println(localDate);
LocalDateTime now= LocalDateTime.now();
System.out.println(now);
Calendar calendar=Calendar.getInstance();
}
private static void testInstant() throws InterruptedException {
Instant start=Instant.now();
Thread.sleep(1000);
Instant end= Instant.now();
Duration duration= Duration.between(start,end);
System.out.println(duration.toMillis());
}
private static void testDuration(){
LocalTime time=LocalTime.now();
LocalTime before= time.minusHours(1);
Duration duration = Duration.between(time,before);
System.out.println(duration.toHours());
}
private static void testPeriod(){
Period period=Period.between(LocalDate.of(2014,1,10),LocalDate.of(2019,1,1));
System.out.println(period.getYears());
System.out.println(period.getMonths());
System.out.println(period.getDays());
}
private static void testDateFormat(){
LocalDate localDate= LocalDate.now();
String format1= localDate.format(DateTimeFormatter.BASIC_ISO_DATE);
String format2= localDate.format(DateTimeFormatter.ISO_LOCAL_DATE);
// String format2= localDate.format(DateTimeFormatter.ISO_LOCAL_TIME);
System.out.println(format1);
System.out.println(format2);
DateTimeFormatter dtf= DateTimeFormatter.ofPattern("yyyy/MM/dd");
System.out.println(localDate.format(dtf));
}
private static void testDateParse(){
String date1="20191101";
LocalDate localDate=LocalDate.parse(date1,DateTimeFormatter.BASIC_ISO_DATE);
System.out.println(localDate);
String date2="2019-11-01";
LocalDate localDate1=LocalDate.parse(date2,DateTimeFormatter.ofPattern("yyyy-MM-dd"));
System.out.println(localDate1);
}
}
methodReference
package com.fcc.lambda;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
/**
* @description
* @auther feicongcong
* @date 2019/11/7
*/
public class MethodReference {
public static void main(String[] args){
Consumer<String> consumer=s-> System.out.println(s);
useConsumer(consumer,"Hello alex");
useConsumer(s-> System.out.println(s),"Hello alex");
//使用方法推导成FunctionalInterface(函数接口)
useConsumer( System.out::println,"Hello alex");
List<Apple> list= Arrays.asList(new Apple("green",110),new Apple("ayellow",120));
System.out.println(list);
//ascil表顺序
list.sort((a1,a2)->a1.getColor().compareTo(a2.getColor()));
System.out.println(list);
//方法推导
list.stream().forEach(System.out::println);
int value = Integer.parseInt("123");
//静态方法可推导
//类变量
//实例方法
//构造函数
Function<String,Integer> f=Integer::parseInt;
Integer result = f.apply("234");
System.out.println(result);
BiFunction<String,Integer,Character> f2 = String::charAt;
Character c = f2.apply("hello",2);
System.out.println(c);
String str=new String("hello");
Function<Integer,Character> f3 = str::charAt;
Character c2 =f3.apply(4);
System.out.println(c2);
Supplier<String> supplier = String::new;
String s=supplier.get();
System.out.println(s);
BiFunction<String,Long,Apple> appleBiFunction=Apple::new;
Apple apple=appleBiFunction.apply("red",100L);
System.out.println(apple);
ThreeFunction<String,Long,String,ComplexApple> threeFunction=ComplexApple::new;
ComplexApple complexApple=threeFunction.apply("green",120L,"富士");
System.out.println(complexApple);
List<Apple> list2= Arrays.asList(new Apple("green",110),new Apple("ayellow",120));
//方法推导比匿名内部类代码更简洁
list2.sort(Comparator.comparing(Apple::getColor));
}
private static <T> void useConsumer(Consumer<T> consumer,T t){
consumer.accept(t);
consumer.accept(t);
}
}
package com.fcc.lambda;
@FunctionalInterface
public interface ThreeFunction<T,U,K,R> {
R apply(T t,U u,K k);
}
simpleStream
package com.fcc.lambda;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* @description
* @auther feicongcong
* @date 2019/11/8
*/
public class SimpleStream {
public static void main(String[] args){
List<Dish> menu= Arrays.asList(
new Dish("pork",false,800,Dish.Type.MEAT),
new Dish("beef",false,700,Dish.Type.MEAT),
new Dish("chicken",false,800,Dish.Type.MEAT),
new Dish("french fries",false,530,Dish.Type.OTHER),
new Dish("rice",true,350,Dish.Type.OTHER),
new Dish("season fruit",true,350,Dish.Type.OTHER),
new Dish("pizza",true,550,Dish.Type.OTHER),
new Dish("prawns",false,300,Dish.Type.FISH),
new Dish("salmon",false,450,Dish.Type.FISH)
);
// System.out.println(getDishNamesByCollections(menu));
System.out.println(getDishNameByStream(menu));
Stream<Dish> dishStream = Stream.of(new Dish("prawns",false,300,Dish.Type.FISH),
new Dish("salmon",false,450,Dish.Type.FISH));
dishStream.forEach(System.out::println);
}
private static List<String> getDishNameByStream(List<Dish> menu){
return menu.parallelStream().filter(d->{
// try {
// Thread.sleep(10000L);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
return d.getCalories()<400;})
.sorted(Comparator.comparing(Dish::getCalories)).map(Dish::getName).collect(Collectors.toList());
}
private static List<String> getDishNamesByCollections(List<Dish> menu){
List<Dish> lowCalories= new ArrayList<>();
for(Dish d:menu){
if(d.getCalories()<400) {
lowCalories.add(d);
}
}
try{
Thread.sleep(100000);
}catch (Exception e){
e.printStackTrace();
}
Collections.sort(lowCalories,(d1,d2)->Integer.compare(d1.getCalories(),d2.getCalories()));
// Collections.sort(lowCalories, Comparator.comparing(Dish::getCalories));
List<String> dishNameList=new ArrayList<>();
for(Dish d:lowCalories){
dishNameList.add(d.getName());
}
return dishNameList;
}
}
createStrean
package com.fcc.lambda;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
/**
* @description
* @auther feicongcong
* @date 2019/11/8
*/
public class CreateStream {
//Collection创建stream
public static void main(String[] args){
// createStreamFromArrays().forEach(System.out::println);
createStreamFromFile();
}
private static Stream<String> createStreamFromCollection(){
List<String> list=Arrays.asList("hello","alex","feicongcong","world","stream");
return list.stream();
}
private static Stream<String> createStreamFromValues(){
return Stream.of("hello","alex","feicongcong","world","stream");
}
private static Stream<String> createStreamFromArrays(){
return Arrays.stream(new String[]{"hello","alex","feicongcong","world","stream"});
}
private static Stream<String> createStreamFromFile(){
Path path = Paths.get("D:\\项目\\龙口智慧工地项目\\jdk8\\src\\main\\resources\\service.properties");
try(Stream<String> lines= Files.lines(path)){
lines.forEach(System.out::println);
return lines;
}catch (Exception e){
e.printStackTrace();
}
return null;
}
}
@Data
@AllArgsConstructor
//@NoArgsConstructor
public class Dish {
private final String name;
private final boolean vegetarian;
private final int calories;
private final Type type;
public enum Type{MEAT,FISH,OTHER};
}
StreamMap
package com.fcc.lambda;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* @description
* @auther feicongcong
* @date 2019/11/10
*/
public class StreamMap {
public static void main(String[] args){
List<Integer> list = Arrays.asList(1,2,3,4,5,6,6,7,7,1) ;
List<Integer> result =list.stream().map(i->i*2).collect(Collectors.toList());
System.out.println(result);
listDish().stream().map(d->d.getName()).forEach(System.out::println);
List<String> dishs=listDish().stream().map(d->d.getName()).collect(Collectors.toList());
System.out.println(dishs);
//flatmap flat 扁平化
String[] words={"hello","World"};
Stream<String[]> stream=Arrays.stream(words).map(w->w.split(""));
Stream<String> stringStream=stream.flatMap(Arrays::stream);
stringStream.distinct().forEach(System.out::println);
}
private static List<Dish> listDish(){
List<Dish> menu=Arrays.asList(
new Dish("pork",false,800,Dish.Type.MEAT),
new Dish("beef",false,700,Dish.Type.MEAT),
new Dish("chicken",false,800,Dish.Type.MEAT),
new Dish("french fries",false,530,Dish.Type.OTHER),
new Dish("rice",true,350,Dish.Type.OTHER),
new Dish("season fruit",true,350,Dish.Type.OTHER),
new Dish("pizza",true,550,Dish.Type.OTHER),
new Dish("prawns",false,300,Dish.Type.FISH),
new Dish("salmon",false,450,Dish.Type.FISH)
);
return menu;
}
}
streamFind
public class StreamFind {
public static void main(String[] args){
Stream<Integer> stream = Arrays.stream(new Integer[]{1,2,3,4,5,6,7});
Optional<Integer> optional=stream.filter(i->i%2==0).findAny();
System.out.println(optional.get());
stream = Arrays.stream(new Integer[]{1,2,3,4,5,6,7});
Optional<Integer> optional3=stream.filter(i->i>1).findAny();
System.out.println(optional3.get());
System.out.println(optional3.orElse(-1));
stream = Arrays.stream(new Integer[]{1,2,3,4,5,6,7});
Optional<Integer> optional2=stream.filter(i->i%2==0).findFirst();
System.out.println(optional2.get());
// System.out.println(optional2.get());
optional2.ifPresent(System.out::println);
System.out.println(optional2.filter(i->i==2).get());
}
}
streamMatch
public class StreamMatch {
//filter
//limit
//skip
//map
//flatmap
//distinct
//match(boolean nonematch|anymatchl|allmatch )
//find
//reduce
public static void main(String[] args){
Stream<Integer> stream= Arrays.stream(new Integer[]{1,2,3,4,5,6,7});
boolean matched=stream.allMatch(i->i>10);
System.out.println(matched);
//这样会报错,流只能用一次,中断后就不能用
// stream.anyMatch(i->i>6);
Stream<Integer> stream1= Arrays.stream(new Integer[]{1,2,3,4,5,6,7});
boolean matched1=stream1.anyMatch(i->i>6);
System.out.println(matched1);
assert matched:"sfsfs";
stream =Arrays.stream(new Integer[]{1,2,3,4,5,6});
boolean matched2=stream.noneMatch(i->i>10);
System.out.println(matched2);
}
}
streamReduce
public class StreamReduce {
public static void main(String[] args) {
Stream<Integer> stream = Arrays.stream(new Integer[]{1, 2, 3, 4, 5, 6, 7});
// Integer redult =stream.reduce(0,(i,j)->i+j);
Integer redult =stream.reduce(0,Integer::sum);
System.out.println(redult);
stream = Arrays.stream(new Integer[]{1, 2, 3, 4, 5, 6, 7});
stream.reduce((i,j)->i+j).ifPresent(System.out::println);
stream = Arrays.stream(new Integer[]{1, 2, 3, 4, 5, 6, 7});
stream.reduce((i,j)->{
return i>j?i:j;
}).ifPresent(System.out::println);
stream = Arrays.stream(new Integer[]{1, 2, 3, 4, 5, 6, 7});
stream.reduce(Integer::min).ifPresent(System.out::println);
stream = Arrays.stream(new Integer[]{1, 2, 3, 4, 5, 6, 7});
int result2 = stream.filter(i->i%2==0).reduce(1,(i,j)->i*j);
Optional.of(result2).ifPresent(System.out::println);
}
}
optional
public class OptionalUsage {
public static void main(String[] args){
Optional<Insurance> insuranceOptional = Optional.<Insurance>empty();
Optional<Insurance> insuranceOptional1 = Optional.of(new Insurance());
insuranceOptional1.get();
Optional<Object> objectOptional = Optional.ofNullable(null);
objectOptional.orElseGet(Insurance::new);
objectOptional.orElse(new Insurance());
objectOptional.orElseThrow(RuntimeException::new);
objectOptional.orElseThrow(()->new RuntimeException("not has reference"));
Optional<Insurance> insuranceOptional2 = Optional.of(new Insurance());
Insurance insurance = insuranceOptional2.filter(i -> i.getName() != null).get();
Optional<String> nameOptional = insuranceOptional2.map(i -> i.getName());
System.out.println(nameOptional.orElse("emptyValue"));
System.out.println(nameOptional.isPresent());
nameOptional.ifPresent(System.out::println);
}
// private static String getInsuranceName(Insurance insurance){
//
// }
}
public class OptionalInAction {
//function programming style
//just tell how to work not do work 告诉怎么做而不是做什么
public static void main(String[] args){
System.out.println(getInsuanceNameByOptional(null));
Optional.ofNullable(getInsuanceNameByOptional(null)).ifPresent(System.out::println);
}
private static String getInsuanceNameByOptional(Person person){
return Optional.ofNullable(person).flatMap(Person::getCar).flatMap(Car::getInsurance).map(Insurance::getName).orElse("unknow");
}
}
NumericStream
public class NumericStream {
public static void main(String[] args) {
Stream<Integer> stream = Arrays.stream(new Integer[]{1, 2, 3, 4, 5, 6, 7});
// Integer result = stream.filter(i -> i.intValue() > 3).reduce(0, Integer::sum);
//Integer 转 int
int result = stream.mapToInt(i -> i.intValue()).filter(i->i>3).sum();
System.out.println(result);
// int 4byte/32bit
int a = 9;
//匹配勾股定理,box() int转回Integer
IntStream.rangeClosed(1, 100)
.filter(b -> Math.sqrt(a * a + b * b) % 1 == 0).boxed().map(x->new int[]{a,x,(int)Math.sqrt(a*a+x*x)})
.forEach(r->System.out.println("a="+r[0]+",b="+r[1]+",c="+r[2]));
IntStream.rangeClosed(1, 100)
.filter(b -> Math.sqrt(a * a + b * b) % 1 == 0).mapToObj(x->new int[]{a,x,(int)Math.sqrt(a*a+x*x)});
}
}
Collectors
public class CollectorAction {
public final static List<Dish> menu= Arrays.asList(
new Dish("pork",false,800,Dish.Type.MEAT),
new Dish("beef",false,700,Dish.Type.MEAT),
new Dish("chicken",false,800,Dish.Type.MEAT),
new Dish("french fries",false,530,Dish.Type.OTHER),
new Dish("rice",true,350,Dish.Type.OTHER),
new Dish("season fruit",true,350,Dish.Type.OTHER),
new Dish("pizza",true,550,Dish.Type.OTHER),
new Dish("prawns",false,300,Dish.Type.FISH),
new Dish("salmon",false,450,Dish.Type.FISH)
);
public static void main(String[] args){
// testAveragingDouble();
// testAveragingInt();
// testAveragingLong();
// testCount();
// testGroupingByFunction();
// testGroupingByFunctionAndCollector();
testSummarizingInt();
}
private static void testAveragingDouble(){
Optional.ofNullable(menu.stream().collect(Collectors.averagingDouble(Dish::getCalories))).ifPresent(System.out::println);
}
private static void testAveragingInt(){
Optional.ofNullable(menu.stream().collect(Collectors.averagingInt(Dish::getCalories))).ifPresent(System.out::println);
Optional.ofNullable(menu.stream().collect(Collectors.collectingAndThen(
Collectors.averagingInt(Dish::getCalories),a->"averagingInt="+a))).ifPresent(System.out::println);
}
private static void testAveragingLong(){
Optional.ofNullable(menu.stream().collect(Collectors.averagingLong(Dish::getCalories))).ifPresent(System.out::println);
}
private static void testCollectingAndThen(){
List<Dish> list=menu.stream().filter(d->d.getType().equals(Dish.Type.MEAT)).collect(Collectors.collectingAndThen(
Collectors.toList(), Collections::unmodifiableList
));
list.add(new Dish("salmon",false,450,Dish.Type.FISH));//报错
}
private static void testCount(){
Optional.of(menu.stream().collect(Collectors.counting())).ifPresent(System.out::println);
}
private static void testGroupingByFunction(){
Optional.of(menu.stream().collect(Collectors.groupingBy(Dish::getType))).ifPresent(System.out::println);
}
private static void testGroupingByFunctionAndCollector(){
Optional.of(menu.stream().collect(Collectors.groupingBy(Dish::getType,Collectors.counting())))
.ifPresent(System.out::println);
Optional.of(menu.stream().collect(Collectors.groupingBy(Dish::getType,Collectors.averagingInt(Dish::getCalories))))
.ifPresent(System.out::println);
}
private static void testGroupingByFunctionAndSupplierAndCollector(){
Map<Dish.Type, Double> map = menu.stream().collect(Collectors.groupingBy(Dish::getType, TreeMap::new,Collectors.averagingInt(Dish::getCalories)));
}
private static void testSummarizingInt(){
IntSummaryStatistics collect = menu.stream().collect(Collectors.summarizingInt(Dish::getCalories));
Optional.of(collect).ifPresent(System.out::println);
}
}
public class CollectorsAction2 {
public static void main(String[] args){
testJoining();
testJoining1();
testMaxBy();
}
private static void testGroupingByConcurrent(){
ConcurrentMap<Dish.Type, List<Dish>> collect = menu.stream().collect(Collectors.groupingByConcurrent(Dish::getType));
Optional.ofNullable(collect.getClass()).ifPresent(System.out::println);
}
private static void testGroupingByConcurrentWithFunctionAndCollector(){
ConcurrentMap<Dish.Type, Double> collect = menu.stream().collect(Collectors.groupingByConcurrent(Dish::getType, Collectors.averagingInt(Dish::getCalories)));
Optional.ofNullable(collect.getClass()).ifPresent(System.out::println);
}
private static void testGroupingByConcurrentWithFunctionAndSupplierAndCollector(){
ConcurrentMap<Dish.Type, Double> collect = menu.stream().collect(Collectors.groupingByConcurrent(Dish::getType, ConcurrentSkipListMap::new,Collectors.averagingInt(Dish::getCalories)));
Optional.ofNullable(collect.getClass()).ifPresent(System.out::println);
}
public static void testJoining(){
Optional.ofNullable(menu.stream().map(Dish::getName).collect(Collectors.joining())).ifPresent(System.out::println);
Optional.ofNullable(menu.stream().map(Dish::getName).collect(Collectors.joining(","))).ifPresent(System.out::println);
System.out.println(menu.stream().map(Dish::getName).collect(Collectors.joining(",")));
}
public static void testJoining1(){
Optional.ofNullable(menu.stream().map(Dish::getName).collect(Collectors.joining(",","Names[","]"))).ifPresent(System.out::println);
}
public static void testMapping(){
Optional.ofNullable(menu.stream().collect(Collectors.mapping(Dish::getName,Collectors.joining(",")))).ifPresent(System.out::println);
}
public static void testMaxBy(){
Optional.ofNullable(menu.stream().collect(Collectors.maxBy(Comparator.comparingInt(Dish::getCalories)))).ifPresent(System.out::println);
}
public static void testMinxBy(){
Optional.ofNullable(menu.stream().collect(Collectors.minBy(Comparator.comparingInt(Dish::getCalories)))).ifPresent(System.out::println);
}
}
public class CollectorsAction3 {
public static void main(String[] args){
testPartition();
testReduceBinaryOperator();
testSummarizingDouble();
}
private static void testPartition(){
Map<Boolean, List<Dish>> collect = menu.stream().collect(Collectors.partitioningBy(Dish::isVegetarian));
Optional.ofNullable(collect).ifPresent(System.out::println);
}
private static void testPartitionByAndCollector(){
Map<Boolean, Double> collect = menu.stream()
.collect(Collectors.partitioningBy(Dish::isVegetarian, Collectors.averagingInt(Dish::getCalories)));
Optional.ofNullable(collect).ifPresent(System.out::println);
}
private static void testReduceBinaryOperator(){
menu.stream()
.collect(Collectors.reducing(
BinaryOperator.maxBy(
Comparator.comparingInt(Dish::getCalories)))).ifPresent(System.out::println);
menu.stream()
.map(Dish::getCalories).collect(Collectors.reducing(Integer::min));
}
private static void testReduceBinaryOperator1(){
menu.stream()
.map(Dish::getCalories).collect(Collectors.reducing(0,(d1,d2)->d1+d2));
}
private static void testReduceBinaryOperator2(){
menu.stream()
.collect(Collectors.reducing(0,Dish::getCalories,(d1,d2)->d1+d2));
}
private static void testSummarizingDouble(){
Optional.ofNullable(menu.stream().collect(Collectors.summarizingDouble(Dish::getCalories))).ifPresent(System.out::println);
Optional.ofNullable(menu.stream().collect(Collectors.summarizingLong(Dish::getCalories))).ifPresent(System.out::println);
Optional.ofNullable(menu.stream().collect(Collectors.summarizingInt(Dish::getCalories))).ifPresent(System.out::println);
}
}
public class CollectorsAction4 {
public static void main(String[] args){
testSummingDouble();
testToConcurrentMapWithBinaryOperator();
}
private static void testSummingDouble(){
Double collect = menu.stream().collect(Collectors.summingDouble(Dish::getCalories));
Optional.ofNullable(collect).ifPresent(System.out::println);
Optional.ofNullable(
menu.stream().map(Dish::getCalories).mapToInt(Integer::intValue).sum())
.ifPresent(System.out::println);
}
private static void testSummingLong(){
Optional.ofNullable( menu.stream().collect(Collectors.summingLong(Dish::getCalories)))
.ifPresent(System.out::println);
Optional.ofNullable( menu.stream().collect(Collectors.summingInt(Dish::getCalories)))
.ifPresent(System.out::println);
}
private static void testToCollection(){
Optional.ofNullable( menu.stream().collect(Collectors.toCollection(LinkedList::new)))
.ifPresent(System.out::println);
}
private static void testToConcurrentMap(){
Optional.ofNullable( menu.stream().collect(Collectors.toConcurrentMap(Dish::getName,Dish::getCalories)))
.ifPresent(System.out::println);
}
private static void testToConcurrentMapWithBinaryOperator(){
Optional.ofNullable( menu.stream().collect(Collectors.toConcurrentMap(Dish::getType,v->1L,(a,b)->a+b)))
.ifPresent(System.out::println);
}
private static void testToList(){
Optional.ofNullable( menu.stream().filter(Dish::isVegetarian).collect(Collectors.toList()))
.ifPresent(System.out::println);
}
private static void testToMap(){
Optional.ofNullable( menu.stream()
.collect(Collectors.toMap(Dish::getType,v->1L,(a,b)->a+b, Hashtable::new)))
.ifPresent(System.out::println);
Optional.ofNullable(menu.stream().collect(Collectors.collectingAndThen(
Collectors.toMap(Dish::getName,Dish::getCalories), Collections::synchronizedMap
))).ifPresent(v->{
System.out.println(v);
System.out.println(v.getClass());
});
}
}
ParallelProcessing
public class ParallelProcessing {
public static void main(String[] args){
// System.out.println(
// Runtime.getRuntime().availableProcessors()
// );
//并行设置核数
System.setProperty("java.util.concurrent.ForkJoinPool.common.parallelism","20");
System.out.println("The best process time(normalAdd)=>"+meaureSumPerformance(ParallelProcessing::normalAdd,100_000_000)+"ms");
// System.out.println("The best process time(iterateStream)=>"+meaureSumPerformance(ParallelProcessing::iterateStream,10_000_000)+"ms");
// System.out.println("The best process time(parallelStream)=>"+meaureSumPerformance(ParallelProcessing::parallelStream,10_000_000)+"ms");
// System.out.println("The best process time(parallelStream2)=>"+meaureSumPerformance(ParallelProcessing::parallelStream2,10_000_000)+"ms");
System.out.println("The best process time(parallelStream3)=>"+meaureSumPerformance(ParallelProcessing::parallelStream3,100_000_000)+"ms");
}
private static long meaureSumPerformance(Function<Long,Long> adder,long limit){
long fastest=Long.MAX_VALUE;
for(int i=0;i<10;i++){
long startTimestamp=System.currentTimeMillis();
long result=adder.apply(limit);
long duration = System.currentTimeMillis()-startTimestamp;
// System.out.println("The result of sum=>"+result);
if(duration<fastest){fastest= duration;}
}
return fastest;
}
private static long iterateStream(long limit){
return Stream.iterate(1L,i->i+1).limit(limit).reduce(0L,Long::sum);
}
private static long parallelStream(long limit){
return Stream.iterate(1L,i->i+1).parallel().
limit(limit).reduce(0L,Long::sum);
}
private static long parallelStream2(long limit){
return Stream.iterate(1L,i->i+1).mapToLong(Long::longValue).parallel().
limit(limit).reduce(0L,Long::sum);
}
private static long parallelStream3(long limit){
return LongStream.rangeClosed(1,limit).parallel().reduce(0L,Long::sum);
}
private static long normalAdd(long limit){
long result =0L;
for(long i=1L;i<limit;i++){
result+=i;
}
return result;
}
}
FutureAction
package com.fcc.lambda;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
/**
* @see FutureInAction2
* @since 1.0
*/
public class FutureInAction2 {
public static void main(String[] args) throws Exception{
ExecutorService executorService= Executors.newSingleThreadExecutor();
Future<String> future=executorService.submit(()->{
try {
Thread.sleep(1000L);
return "Im finish";
} catch (InterruptedException e) {
e.printStackTrace();
return "Im error";
}
});
// String value=future.get(5, TimeUnit.SECONDS);
while (!future.isDone()){
Thread.sleep(100L);
}
// System.out.println(value);
System.out.println(future.get());
executorService.shutdownNow();
}
}
package com.fcc.lambda;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
/**
* @see FutureAction3
* @since 1.0
*/
public class FutureAction3 {
public static void mian(String[] args){}
private static <T> Future<T> invoke(Callable<T> callable){
AtomicReference<T> result = new AtomicReference<>();
AtomicBoolean finished = new AtomicBoolean(false);
Thread t = new Thread(()->{
T value = callable.action();
result.set(value);
finished.set(true);
});
t.start();
Future<T> future = new Future<T>(){
@Override
public T get() {
return result.get();
}
@Override
public boolean isDone() {
return finished.get();
}
};
return future;
}
private interface Future<T>{
T get();
boolean isDone();
}
private interface Callable<T>{
T action();
}
}