Java学习-聚合操作

准备10个Hero对象,hp和damage都是随机数。
分别用传统方式和聚合操作的方式,把hp第三高的英雄名称打印出来

 1 package generic_Lambda;
 2 
 3 import java.util.ArrayList;
 4 import java.util.Arrays;
 5 import java.util.Collections;
 6 import java.util.List;
 7 import java.util.Random;
 8 
 9 import charactor.Hero;
10 
11 public class testAggregate {
12 
13     public static void main(String[] args) {
14         Random r = new Random();
15         List<Hero> heros = new ArrayList<Hero>();
16         for (int i = 0; i < 5; i++) {
17             heros.add(new Hero("hero " + i, r.nextInt(1000), r.nextInt(100)));
18         }
19         System.out.println("源数据:\n" + heros);
20         System.out.println("把hp第三高的英雄名称打印出来");
21         System.out.println("传统方式(冒泡排序):");
22         // 冒泡排序思想
23         for (int j = heros.size() - 1; j >= heros.size() - 3; j--) {
24             for (int i = 0; i + 1 <= j; i++) {
25                 if (heros.get(i).hp > heros.get(i + 1).hp) {
26                     Hero tmp = heros.get(i);
27                     heros.set(i, heros.get(i + 1));
28                     heros.set(i + 1, tmp);
29                 }
30             }
31         }
32         System.out.println("\thp第三高的英雄名是:" + heros.get(heros.size() - 3).name);
33 
34         System.out.println("传统方式(Collections.sort()):");
35         Collections.sort(heros, (h1, h2) -> h2.hp > h1.hp ? 1 : -1);
36         System.out.println("\thp第三高的英雄名是:" + heros.get(2).name);
37 
38         System.out.println("采用聚合方式:");
39         Hero maxHPHero = heros.stream().sorted((h1, h2) -> h2.hp > h1.hp ? 1 : -1).skip(2).findFirst().get();  //跳过头两个,然后findFist()就是第三大的数据
40         System.out.println("\thp第三高的英雄名是:" + maxHPHero.name);
41     }
42 }

效果图:

 

posted @ 2020-01-25 16:11  细雨轻风  阅读(570)  评论(0编辑  收藏  举报