几种Java8 Lambda表达式的使用

最近在工作中,使用到了两种Lambda表达,列举一下

1、求和

   /**
     * 获取总数
     *
     * @return
     */
    private static Long getTotalCoin() {
        ArrayList<Person> personList = Lists.newArrayList();
        personList.add(new Person(1, "张三", 23L));
        personList.add(new Person(2, "李四", 12L));
        personList.add(new Person(3, "王五", 20L));
        personList.add(new Person(3, "小六", 73L));
        // 这里求和
        return personList.stream().mapToLong(person -> person.getIncomeCoin()).sum();
    }
    public static class Person{
        /** id */
        private int id;
        /** 姓名*/
        private String name;
        /** 收入金币数*/
        private Long incomeCoin;

        public Person(int id, String name, Long incomeCoin) {
            this.id = id;
            this.name = name;
            this.incomeCoin = incomeCoin;
        }

        public Long getIncomeCoin() {
            return incomeCoin;
        }
    }

2、List 转为Map

private static Map<Integer, Coin> toCoinMap() {
        ArrayList<Coin> coinList = Lists.newArrayList();
        coinList.add(new Coin(1, 10, "玛瑙", 1));
        coinList.add(new Coin(2, 20, "玄铁", 1));
        coinList.add(new Coin(3, 30, "天命", 2));
        // 这里转换成以id为key,coin对象为value的Map集合
        return coinList.stream().collect(Collectors.toMap(Coin::getId, coin -> coin));
  }
 public static class Coin{
        /** id */
        private int id;
        /** 价格 */
        private int price;
        /** 名称*/
        private String name;
        /** 类型*/
        private int type;

        public Coin(int id, int price, String name, int type) {
            this.id = id;
            this.price = price;
            this.name = name;
            this.type = type;
        }
       // getter and setter
       ...

3、foreach,过滤

private static List<Coin> getPriceByTypeId(int type) {
        ArrayList<Coin> coinList = Lists.newArrayList();
        coinList.add(new Coin(1,10,"玛瑙",1));
        coinList.add(new Coin(2,20,"玄铁",1));
        coinList.add(new Coin(3,30,"天命",2));
        // 这个通过type获取符合条件的类型集合
      return coinList.stream().filter(coin -> type == coin.getType()).collect(Collectors.toList());
    } 

4、list去重

 /**
     * list 去重
     * @return
     */
    public static List<Integer> distinct() {
        ArrayList<Integer> integerList = Lists.newArrayList(1, 9, 4, 5, 5, 3, 6, 7, 8, 6, 7, 34, 23, 12, 89);
        List<Integer> result = integerList.stream().distinct().collect(Collectors.toList());
        System.out.printf("%s", result.toString());
        return result;
    }
输出

[1, 9, 4, 5, 3, 6, 7, 8, 34, 23, 12, 89]

其它

传送:这个写得也不错

你可能感兴趣的:(java)