找回密码
 立即注册
搜索
热搜: 活动 交友 discuz
查看: 160|回复: 2

Java8 学习

[复制链接]

373

主题

55

回帖

1944

积分

管理员

积分
1944
发表于 2018-12-12 20:24:58 | 显示全部楼层 |阅读模式
经过一番苦战,终于把Java8 的绝大部分内容学完了,啃书还真心不容易呢



返回一个热量低于400的卡路里并按照热量升序获取菜肴名称

  1. public class Dish {
  2.         private final String name;
  3.         private final boolean vegetarian;
  4.         private final int calories;
  5.         private final Type type;

  6.         public enum Type {
  7.                 MEAT, FISH, OTHER
  8.         }
  9.         
复制代码


结果:
[season fruit, prawns, rice]




  1. private List<Dish> menu = Arrays.asList(new Dish("pork", false, 800, Dish.Type.MEAT),
  2.                         new Dish("beef", false, 700, Dish.Type.MEAT), new Dish("chicken", false, 400, Dish.Type.MEAT),
  3.                         new Dish("french fries", true, 530, Dish.Type.OTHER), new Dish("rice", true, 350, Dish.Type.OTHER),
  4.                         new Dish("season fruit", true, 120, Dish.Type.OTHER), new Dish("pizza", true, 550, Dish.Type.OTHER),
  5.                         new Dish("prawns", false, 300, Dish.Type.FISH), new Dish("salmon", false, 450, Dish.Type.FISH));;
复制代码

Java8之前


Java8 写法



stream 操作分为
数据源
中间操作

终端操作

数组-> Stream    Arrays.stream(T[] arrays)
distinct-> toSet()

流操作的模式
过滤:filter(predicate), distinct(),limit(n),skip(n),
切片
查找:findFirst(),findAny()
匹配:allMatch(predicate),anyMatch(predicate),noneMatch(predicate)
映射:map(function),flatMap(function)
归约:reduce()


IntStream-> boxed()-> collect()

  1.         private List<Dish> menu = Arrays.asList(new Dish("pork", false, 800, Dish.Type.MEAT),
  2.                         new Dish("beef", false, 700, Dish.Type.MEAT), new Dish("chicken", false, 400, Dish.Type.MEAT),
  3.                         new Dish("french fries", true, 530, Dish.Type.OTHER), new Dish("rice", true, 350, Dish.Type.OTHER),
  4.                         new Dish("season fruit", true, 120, Dish.Type.OTHER), new Dish("pizza", true, 550, Dish.Type.OTHER),
  5.                         new Dish("prawns", false, 300, Dish.Type.FISH), new Dish("salmon", false, 450, Dish.Type.FISH));;

  6.         @Test
  7.         public void test00() {
  8.                 List<Dish> lowCaloricDishes = new ArrayList<>();
  9.                 for (Dish d : menu) {
  10.                         if (d.getCalories() < 400) {
  11.                                 lowCaloricDishes.add(d);
  12.                         }
  13.                 }
  14.                 Collections.sort(lowCaloricDishes, new Comparator<Dish>() {
  15.                         public int compare(Dish d1, Dish d2) {
  16.                                 return Integer.compare(d1.getCalories(), d2.getCalories());
  17.                         }
  18.                 });
  19.                 List<String> lowCaloricDishesName = new ArrayList<>();
  20.                 for (Dish d : lowCaloricDishes) {
  21.                         lowCaloricDishesName.add(d.getName());
  22.                 }

  23.                 System.out.println(lowCaloricDishesName);
  24.         }

  25.         @Test
  26.         public void test01() {
  27.                 // 获取卡路里小于400 ,热量顺序排列获取菜肴名称
  28.                 List<String> list = menu.stream().filter(item -> item.getCalories() < 400)
  29.                                 .sorted((i1, i2) -> Integer.compare(i1.getCalories(), i2.getCalories())).map(item -> item.getName())
  30.                                 .collect(Collectors.toList());
  31.                 System.out.println(list);

  32.                 // 写法2, 使用辅助方法
  33.                 List<String> list2 = menu.stream().filter(item -> item.getCalories() < 400)
  34.                                 .sorted(Comparator.comparing(Dish::getCalories)).map(Dish::getName).collect(Collectors.toList());
  35.                 System.out.println(list2);

  36.                 // 写法3,添加方法引用
  37.                 List<String> list3 = menu.stream().filter(Dish::isLose).sorted(Comparator.comparing(Dish::getCalories))
  38.                                 .map(Dish::getName).collect(Collectors.toList());
  39.                 System.out.println(list3);

  40.         }

  41.         @Test
  42.         public void test02() {

  43.                 Map<Type, List<Dish>> list = menu.stream().collect(Collectors.groupingBy(Dish::getType));

  44.                 System.out.println(list);

  45.         }

  46.         @Test
  47.         public void test03() {
  48.                 // ["Hello","World"],你想要返回列表["H","e","l", "o","W","r","d"]。

  49.                 String[] strArr = { "Hello", "World" };
  50.                 List<String> collect = Arrays.stream(strArr).flatMap(str -> Arrays.asList(str.split("")).stream()).distinct()
  51.                                 .collect(Collectors.toList());

  52.                 System.out.println(collect);

  53.                 List<String> collect2 = Arrays.asList(strArr).stream().map(str -> str.split("")).flatMap(Arrays::stream)
  54.                                 .distinct().collect(Collectors.toList());

  55.                 System.out.println(collect2);

  56.         }

  57.         @Test
  58.         public void test04() {
  59.                 // (1) 给定一个数字列表,如何返回一个由每个数的平方构成的列表呢?
  60.                 // 例如,给定[1, 2, 3, 4, 5],应该返回[1, 4, 9, 16, 25]

  61.                 int[] arr = { 1, 2, 3, 4, 5 };
  62.                 List<Integer> collect = Arrays.stream(arr).map(item -> item * item).boxed().collect(Collectors.toList());
  63.                 System.out.println(collect);

  64.         }

  65.         @Test
  66.         public void test05() {
  67.                 // (2) 给定两个数字列表,如何返回所有的数对呢?
  68.                 // 例如,给定列表[1, 2, 3]和列表[3, 4],
  69.                 // 应该返回[(1, 3), (1, 4), (2, 3), (2, 4), (3, 3), (3, 4)]。
  70.                 // 为简单起见,你可以用有两个元素的数组来代
  71.                 // 表数对。

  72.                 List<Integer> alist = Arrays.asList(1, 2, 3);
  73.                 List<Integer> blist = Arrays.asList(3, 4);

  74.                 List<int[]> collect = alist.stream().flatMap(item -> blist.stream().map(bitem -> new int[] { item, bitem }))
  75.                                 .collect(Collectors.toList());
  76.                 for (int[] is : collect) {
  77.                         System.out.println(Arrays.toString(is));
  78.                 }

  79.                 System.out.println("====");

  80.                 // (3) 如何扩展前一个例子,只返回总和能被3整除的数对呢?例如(2, 4)和(3, 3)是可以的。
  81.                 List<int[]> collect2 = alist.stream().flatMap(
  82.                                 item -> blist.stream().filter(bitem -> (item + bitem) % 3 == 0).map(bitem -> new int[] { item, bitem }))
  83.                                 .collect(Collectors.toList());
  84.                 for (int[] is : collect2) {
  85.                         System.out.println(Arrays.toString(is));
  86.                 }

  87.         }

  88.         @Test
  89.         public void test06() {
  90.                 IntStream stream = IntStream.of(1, 2, 3, 4, 5, 6, 7, 12);
  91.                 boolean allMatch = stream.allMatch(item -> item < 12);
  92.                 System.out.println(allMatch);

  93.                 stream = IntStream.of(1, 2, 3, 4, 5, 6, 7, 12);
  94.                 boolean anyMatch = stream.anyMatch(item -> item < 0);
  95.                 System.out.println(anyMatch);

  96.                 stream = IntStream.of(1, 2, 3, 4, 5, 6, 7, 12);
  97.                 boolean anyMatch2 = stream.noneMatch(item -> item < 0);
  98.                 System.out.println(anyMatch2);
  99.         }

  100.         @Test
  101.         public void test07() {
  102.                 IntStream stream = IntStream.of(1, 2, 3, 4, 5, 6, 7);
  103.                 OptionalInt findFirst = stream.findFirst();
  104.                 findFirst.ifPresent(System.out::println);

  105.                 stream = IntStream.of(1, 2, 3, 4, 5, 6, 7);
  106.                 OptionalInt findFirst2 = stream.findAny();
  107.                 findFirst2.ifPresent(System.out::println);
  108.         }

  109.         @Test
  110.         public void test08() {
  111.                 IntStream stream = IntStream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
  112.                 int reduce = stream.reduce(0, (i1, i2) -> i1 + i2);
  113.                 System.out.println(reduce);

  114.                 stream = IntStream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
  115.                 OptionalInt reduce2 = stream.reduce(Integer::sum);
  116.                 reduce2.ifPresent(System.out::println);
  117.         }
  118.        
  119.         @Test
  120.         public void test09() {
  121.                 IntStream stream = IntStream.of(1, 2, 32, 4, 5, 6, 7, 8, 9, 10);
  122.                 OptionalInt max = stream.max();
  123.                 System.out.println(max);
  124.                
  125.                 List<Integer> asList = Arrays.asList(1,2,32,4,5,6,7,8,9,10);
  126.                 Integer reduce = asList.stream().reduce(0, Math:: max);
  127.                 System.out.println(reduce);
  128.         }
  129.        

  130.         @Test
  131.         public void test10() {
  132.                 IntStream stream = IntStream.of(1, 2, 32, 4, 5, 6, 7, 8, 9, 10);
  133.                 int sum = stream.sum();
  134.                 System.out.println(sum);
  135.                

  136.                 List<Integer> asList = Arrays.asList(1,2,32,4,5,6,7,8,9,10);
  137.                 Integer reduce = asList.stream().mapToInt(i->i).sum();
  138.                 System.out.println(reduce);
  139.                
  140.         }
  141.        
  142.         @Test
  143.         public void test11() {
  144.                 IntStream range = IntStream.rangeClosed(0, 100);
  145.                 int sum = range.sum();
  146.                 System.out.println(sum);
  147.         }
  148.        
  149.         @Test
  150.         public void test12() {
  151.                 IntStream rangeClosed = IntStream.rangeClosed(1, 100);
  152.                 rangeClosed.boxed().flatMap(a-> IntStream.rangeClosed(a, 100).filter(b-> Math.sqrt(a*a + b*b) % 1.0 ==0).mapToObj(b-> new int[] {a, b, (int)Math.sqrt(a*a + b*b)})).forEach(item->System.out.println(Arrays.toString(item)));
  153.                
  154.         }
  155.        
  156.         @Test
  157.         public void test13() {
  158.                 Stream<Integer> iterate = Stream.iterate(1, i->i+1);
  159.                 List<Integer> collect = iterate.limit(10).collect(Collectors.toList());
  160.                 System.out.println(collect);
  161.         }
  162.        
  163.         @Test
  164.         public void test14() {
  165.                 IntStream stream = IntStream.of(1, 2, 32, 4, 5, 6, 7, 8, 9, 10);
  166.                 long count = stream.count();
  167.                 System.out.println(count);
  168.                
  169.                 stream = IntStream.of(1, 2, 32, 4, 5, 6, 7, 8, 9, 10);
  170.                 Long collect = stream.boxed().collect(Collectors.counting());
  171.                 System.out.println(collect);
  172.                
  173.                 stream = IntStream.of(1, 2, 32, 4, 5, 6, 7, 8, 9, 10);
  174. //                OptionalInt max = stream.max();
  175.                 Optional<Integer> collect2 = stream.boxed().collect(Collectors.maxBy(Comparator.comparingInt(i->i)));
  176.                 System.out.println(collect2);
  177.                
  178.         }
复制代码




本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

×
回复

使用道具 举报

373

主题

55

回帖

1944

积分

管理员

积分
1944
 楼主| 发表于 2018-12-12 20:26:16 | 显示全部楼层
一个lambda 表达式
引入函数式编程
Stream流概念
数据并行
组合式的异步编程理念
新的日期时间api
Optional 取代null
回复

使用道具 举报

373

主题

55

回帖

1944

积分

管理员

积分
1944
 楼主| 发表于 2018-12-12 22:52:21 | 显示全部楼层
CompletableFuture
  1.         @Test
  2.         public void test01() {
  3.                 // 组合式的异步编程

  4.                 ExecutorService newCachedThreadPool = Executors.newCachedThreadPool();
  5.                 Future<Integer> submit = newCachedThreadPool.submit(() -> 1);

  6.                 // ...

  7.                 try {
  8.                         Integer integer = submit.get(1, TimeUnit.SECONDS);
  9.                         System.out.println(integer);
  10.                 } catch (InterruptedException e) {
  11.                         // TODO Auto-generated catch block
  12.                         e.printStackTrace();
  13.                 } catch (ExecutionException e) {
  14.                         // TODO Auto-generated catch block
  15.                         e.printStackTrace();
  16.                 } catch (TimeoutException e) {
  17.                         // TODO Auto-generated catch block
  18.                         e.printStackTrace();
  19.                 }

  20.         }

  21.         @Test
  22.         public void test02() {

  23.                 // String str = "test";
  24.                 // String remoteMethod = remoteMethod(str);
  25.                 // String remoteMethod = remoteMethod(str);
  26.                 // String remoteMethod = remoteMethod(str);

  27.                 // ...

  28.                 // CompletableFuture<String> remoteMethod = remoteMethod(str);
  29.                 // CompletableFuture<String> remoteMethod = remoteMethod(str);
  30.                 // CompletableFuture<String> remoteMethod = remoteMethod(str);
  31.                 // ..

  32.                 List<String> asList = Arrays.asList("1", "2", "3", "4", "4", "4", "4", "4");

  33.                 long start, end = 0;

  34.                 start = System.currentTimeMillis();
  35.                 List<String> collect = asList.parallelStream().map(str -> str + "," + remoteMethod(str))
  36.                                 .collect(Collectors.toList());
  37.                 end = System.currentTimeMillis();
  38.                 System.out.println(collect);
  39.                 System.out.println(end - start);

  40.         }

  41.         @Test
  42.         public void test03() {
  43.                 List<String> asList = Arrays.asList("1", "2", "3", "4", "4", "4", "4", "4");

  44.                 long start, end = 0;

  45.                 start = System.currentTimeMillis();

  46.                 List<CompletableFuture<String>> collect = asList.stream()
  47.                                 .map(str -> CompletableFuture.supplyAsync(() -> str + "," + remoteMethod(str)))
  48.                                 .collect(Collectors.toList());
  49.                 List<String> collect2 = collect.stream().map(CompletableFuture::join).collect(Collectors.toList());
  50.                 end = System.currentTimeMillis();
  51.                 System.out.println(collect2);
  52.                 System.out.println(end - start);
  53.         }

  54.         @Test
  55.         public void test04() {
  56.                 List<String> asList = Arrays.asList("1", "2", "3", "4", "4", "4", "4", "4");

  57.                 long start, end = 0;

  58.                 start = System.currentTimeMillis();

  59.                 ExecutorService newFixedThreadPool = Executors.newFixedThreadPool(asList.size(), new ThreadFactory() {

  60.                         @Override
  61.                         public Thread newThread(Runnable r) {
  62.                                 Thread thread = new Thread(r);

  63.                                 return thread;
  64.                         }
  65.                 });

  66.                 List<CompletableFuture<String>> collect = asList.stream()
  67.                                 .map(str -> CompletableFuture.supplyAsync(() -> str + "," + remoteMethod(str), newFixedThreadPool))
  68.                                 .collect(Collectors.toList());
  69.                 List<String> collect2 = collect.stream().map(CompletableFuture::join).collect(Collectors.toList());
  70.                 end = System.currentTimeMillis();
  71.                 System.out.println(collect2);
  72.                 System.out.println(end - start);
  73.         }

  74.         public static void main(String[] args) {
  75.                 CompletableFutureTest completableFutureTest = new CompletableFutureTest();
  76.                 List<String> asList = Arrays.asList("1", "2", "3", "4", "4", "4", "4", "4");

  77.                 long start, end = 0;

  78.                 start = System.currentTimeMillis();

  79.                 ExecutorService newFixedThreadPool = Executors.newFixedThreadPool(asList.size(), new ThreadFactory() {

  80.                         @Override
  81.                         public Thread newThread(Runnable r) {
  82.                                 Thread thread = new Thread(r);
  83.                                 thread.setDaemon(true);
  84.                                 return thread;
  85.                         }
  86.                 });

  87.                 List<CompletableFuture<String>> collect = asList
  88.                                 .stream().map(str -> CompletableFuture
  89.                                                 .supplyAsync(() -> str + "," + completableFutureTest.remoteMethod(str), newFixedThreadPool))
  90.                                 .collect(Collectors.toList());
  91.                 List<String> collect2 = collect.stream().map(CompletableFuture::join).collect(Collectors.toList());
  92.                 end = System.currentTimeMillis();
  93.                 System.out.println(collect2);
  94.                 System.out.println(end - start);
  95.         }

  96.         @Test
  97.         public void test05() {
  98.                 List<String> asList = Arrays.asList("1", "2", "5", "4", "7", "4", "77", "4", "54");

  99.                 long start, end = 0;
  100.                 start = System.currentTimeMillis();

  101.                 List<String> collect = asList.parallelStream().map(str -> localMethod(str)).map(str -> remoteMethod(str))
  102.                                 .map(str -> remoteMethod2(str)).collect(Collectors.toList());

  103.                 end = System.currentTimeMillis();

  104.                 System.out.println(collect);
  105.                 System.out.println(end - start);

  106.         }

  107.         @Test
  108.         public void test06() {
  109.                 List<String> asList = Arrays.asList("1", "2", "5", "4", "7", "4", "77", "4", "54");

  110.                 long start, end = 0;
  111.                 start = System.currentTimeMillis();

  112.                 List<String> collect = asList.stream().map(str -> localMethod(str)).map(str -> remoteMethod(str))
  113.                                 .map(str -> remoteMethod2(str)).collect(Collectors.toList());

  114.                 end = System.currentTimeMillis();

  115.                 System.out.println(collect);
  116.                 System.out.println(end - start);

  117.         }

  118.         @Test
  119.         public void test07() {
  120.                 List<String> asList = Arrays.asList("1", "2", "5", "4", "7", "4", "77", "4", "54");

  121.                 long start, end = 0;
  122.                 start = System.currentTimeMillis();

  123.                 Executor pool = Executors.newFixedThreadPool(asList.size());
  124.                 List<CompletableFuture<String>> collect = asList.stream().map(str -> localMethod(str))
  125.                                 .map(str -> CompletableFuture.supplyAsync(() -> remoteMethod(str), pool))
  126.                                 .map(future -> future.thenCompose(str -> CompletableFuture.supplyAsync(() -> remoteMethod2(str), pool)))
  127.                                 .collect(Collectors.toList());
  128.                 List<String> collect2 = collect.stream().map(CompletableFuture::join).collect(Collectors.toList());
  129.                 end = System.currentTimeMillis();

  130.                 System.out.println(collect2);
  131.                 System.out.println(end - start);

  132.         }

  133.         @Test
  134.         public void test08() {
  135.                 List<String> asList = Arrays.asList("1", "2", "5", "4", "7", "4", "77", "4", "54");

  136.                 long start, end = 0;
  137.                 Executor pool = Executors.newFixedThreadPool(asList.size());
  138.                 start = System.currentTimeMillis();
  139.                        
  140.                 List<String> collect = asList.stream().map(str-> remoteMethod3(str)).collect(Collectors.toList());

  141.                 end = System.currentTimeMillis();

  142.                 System.out.println(collect);
  143.                 System.out.println(end - start);
  144.         }
  145.         @Test
  146.         public void test09() {
  147.                 List<String> asList = Arrays.asList("1", "2", "5", "4", "7", "4", "77", "4", "54");
  148.                
  149.                 long start, end = 0;
  150.                 Executor pool = Executors.newFixedThreadPool(asList.size());
  151.                 start = System.currentTimeMillis();
  152.                
  153.                 List<String> collect = asList.parallelStream().map(str-> remoteMethod3(str)).collect(Collectors.toList());
  154.                
  155.                 end = System.currentTimeMillis();
  156.                
  157.                 System.out.println(collect);
  158.                 System.out.println(end - start);
  159.         }
  160.         @Test
  161.         public void test10() {
  162.                 List<String> asList = Arrays.asList("1", "2", "5", "4", "7", "4", "77", "4", "54");
  163.                
  164.                 long start, end = 0;
  165.                 Executor pool = Executors.newFixedThreadPool(asList.size());
  166.                 start = System.currentTimeMillis();
  167.                
  168.                 List<CompletableFuture<String>> collect = asList.stream().map(str-> CompletableFuture.supplyAsync(()-> remoteMethod3(str), pool)).collect(Collectors.toList());
  169.                 CompletableFuture[] array = collect.stream().map(future-> future.thenAccept(System.out:: println)).toArray(size-> new CompletableFuture[size]);
  170. //                CompletableFuture.allOf(array).join();
  171.                 CompletableFuture.anyOf(array).join();
  172.                                
  173. //                                .collect(Collectors.toList());
  174.                
  175.                 end = System.currentTimeMillis();
  176.                
  177.                 System.out.println(end - start);
  178.         }

  179.         public String localMethod(String str) {
  180.                 return "自加工+" + str;
  181.         }

  182.         /**
  183.          * 远程方法
  184.          *
  185.          * @param str
  186.          * @return
  187.          */
  188.         public String remoteMethod(String str) {
  189.                 delay();

  190.                 str += "Call Action";
  191.                 return str;

  192.                 // CompletableFuture<String> futureString = new CompletableFuture<>();
  193.                 // new Thread(()->{
  194.                 // String resultString = str + "Call Action";
  195.                 // futureString.complete(resultString);
  196.                 // }).start();
  197.                 // return futureString;

  198.                 // return CompletableFuture.supplyAsync(()-> str + "Call Action");

  199.         }

  200.         public String remoteMethod2(String str) {
  201.                 delay();

  202.                 str += "@@ Call Action2";
  203.                 return str;
  204.         }

  205.         public String remoteMethod3(String str) {
  206.                 delay2();

  207.                 str += "@@ Call Action2";
  208.                 return str;
  209.         }

  210.         /**
  211.          * 模拟延迟
  212.          */
  213.         public void delay() {
  214.                 try {
  215.                         Thread.sleep(1000);
  216.                 } catch (InterruptedException e) {
  217.                         // TODO Auto-generated catch block
  218.                         e.printStackTrace();
  219.                 }
  220.         }

  221.         public Random random = new Random();

  222.         /**
  223.          * 模拟延迟
  224.          */
  225.         public void delay2() {
  226.                 try {
  227.                         Thread.sleep(random.nextInt(2000));
  228.                 } catch (InterruptedException e) {
  229.                         // TODO Auto-generated catch block
  230.                         e.printStackTrace();
  231.                 }
  232.         }
复制代码
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

Archiver|手机版|小黑屋|Comsenz Inc.

GMT+8, 2024-9-20 10:59 , Processed in 0.042612 second(s), 20 queries .

Powered by Discuz! X3.5

© 2001-2024 Discuz! Team.

快速回复 返回顶部 返回列表