Java 8——Lamada表达式

 利用java8 的lamada表达式,可以用简洁高效的代码来实现一些数据处理。

  (1)List操作

  (2)Map操作

  一、List转Map、分组、过滤、去重、最值和去重

mport java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.TreeSet;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.collectingAndThen;
import static java.util.stream.Collectors.toCollection;

public class Apple {
    private Integer id;
    private String name;
    private BigDecimal money;
    private Integer num;

    public Apple(Integer id, String name, BigDecimal money, Integer num) {
        this.id = id;
        this.name = name;
        this.money = money;
        this.num = num;
    }

    @Override
    public String toString() {
        return "Apple{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", money=" + money +
                ", num=" + num +
                '}';
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public BigDecimal getMoney() {
        return money;
    }

    public void setMoney(BigDecimal money) {
        this.money = money;
    }

    public Integer getNum() {
        return num;
    }

    public void setNum(Integer num) {
        this.num = num;
    }


    public static void main(String[] args) {
        List<Apple> appleList = new ArrayList<>();//存放apple对象集合
        Apple apple1 = new Apple(1, "苹果1", new BigDecimal("3.25"), 10);
        Apple apple2 = new Apple(1, "苹果2", new BigDecimal("1.35"), 20);
        Apple apple3 = new Apple(3, "香蕉", new BigDecimal("2.89"), 30);
        Apple apple4 = new Apple(4, "荔枝", new BigDecimal("9.99"), 40);
        appleList.add(apple1);
        appleList.add(apple2);
        appleList.add(apple3);
        appleList.add(apple4);

        /**
         *分组,List里面的对象元素,以某个属性来分组,这里将id相同的放在一组
         */
        Map<Integer, List<Apple>> groupBy = appleList.stream().collect(Collectors.groupingBy(Apple::getId));
        groupBy.forEach((k, v) -> {
            System.out.print("id=" + k + ", name=");
            v.forEach(apple -> {
                System.out.print(apple.getName() + " ");
            });
            System.out.println();
        });
        System.out.println("\n");
        /**
         * List -> Map
         * 需要注意的是:toMap 如果集合对象有重复的key,会报错Duplicate key ....
         *  apple1,apple12的id都为1。
         *  可以用 (k1,k2)->k1 来设置,如果有重复的key,则保留key1,舍弃key2
         */
        Map<Integer, Apple> appleMap = appleList.stream().collect(Collectors.toMap(Apple::getId, entity -> entity, (k1, k2) -> k1));
        appleMap.forEach((k, v) -> {
            System.out.println("id=" + k + ", name=" + v.getName());
        });
        System.out.println("\n");

        /**
         * 从集合中过滤出来符合条件的元素
         */
        List<Apple> filterList = appleList.stream().filter(a -> a.getName().equals("香蕉")).collect(Collectors.toList());
        filterList.forEach(x -> {
            System.out.println(x.toString());
        });
        System.out.println("\n");

        /**
         * 将集合中的数据按照某个属性求和
         */
        BigDecimal totalMoney = appleList.stream().map(Apple::getMoney).reduce(BigDecimal.ZERO, BigDecimal::add);
        System.err.println("totalMoney:" + totalMoney);
        System.out.println("\n");
        /**
         * 查找流中的最大值和最小值:Collectors.maxBy 和 Collectors.minBy 来计算流中的最大或最小值
         *
         */
        List<BigDecimal> price = new ArrayList<>();
        appleList.forEach(x -> price.add(x.getMoney()));
        Optional<Apple> maxDish = appleList.stream().
                collect(Collectors.maxBy(Comparator.comparing(Apple::getMoney)));
        maxDish.ifPresent(System.out::println);
        Optional<Apple> minDish = appleList.stream().
                collect(Collectors.minBy(Comparator.comparing(Apple::getMoney)));
        minDish.ifPresent(System.out::println);
        System.out.println("\n");
        /**
         * 去重
         */
        List<Apple> unique = appleList.stream().collect(
                collectingAndThen(
                        toCollection(() -> new TreeSet<>(Comparator.comparingLong(Apple::getId))), ArrayList::new));
        unique.forEach(x -> {
            System.out.println("id=" + x.getId() + ", name=" + x.getName());
        });
    }
}

运行结果:

id=1, name=苹果1 苹果2 
id=3, name=香蕉 
id=4, name=荔枝 

id=1, name=苹果1
id=3, name=香蕉
id=4, name=荔枝

Apple{id=3, name='香蕉', money=2.89, num=30}

totalMoney:17.48


Apple{id=4, name='荔枝', money=9.99, num=40}
Apple{id=1, name='苹果2', money=1.35, num=20}

id=1, name=苹果1
id=3, name=香蕉
id=4, name=荔枝

二、Map转List,排序

package com.helloworld.demo;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class LamadaMap {


    public static void main(String[] args) {
        mapSort();
        map2List();
    }
    public static void mapSort() {
        Map<String, Integer> unsortMap = new HashMap<>();
        unsortMap.put("z", 10);
        unsortMap.put("b", 5);
        unsortMap.put("a", 6);
        unsortMap.put("c", 20);
        unsortMap.put("d", 1);
        unsortMap.put("e", 7);
        unsortMap.put("y", 8);
        unsortMap.put("n", 99);
        unsortMap.put("g", 50);
        unsortMap.put("m", 2);
        unsortMap.put("f", 9);

        System.out.println("Original...");
        System.out.println(unsortMap);

        /***
         * sort by keys, a,b,c..., and return a new LinkedHashMap
         * toMap() will returns HashMap by default, we need LinkedHashMap to keep the order.
         */
        Map<String, Integer> result1 = unsortMap.entrySet().stream()
                .sorted(Map.Entry.comparingByKey())
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
                        (oldValue, newValue) -> oldValue, LinkedHashMap::new));
        
        /**
         *   Not Recommend, but it works.
         *   Alternative way to sort a Map by keys, and put it into the "result" map
         */
        Map<String, Integer> result2 = new LinkedHashMap<>();
        unsortMap.entrySet().stream()
                .sorted(Map.Entry.comparingByKey())
                .forEachOrdered(x -> result2.put(x.getKey(), x.getValue()));

        //sort by values, and reserve it, 10,9,8,7,6...
        Map<String, Integer> result3 = unsortMap.entrySet().stream()
                .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
                        (oldValue, newValue) -> oldValue, LinkedHashMap::new));

        //Alternative way
        Map<String, Integer> result4 = new LinkedHashMap<>();
        unsortMap.entrySet().stream()
                .sorted(Map.Entry.<String, Integer>comparingByValue().reversed())
                .forEachOrdered(x -> result4.put(x.getKey(), x.getValue()));

        System.out.println("Sorted...");
        System.out.println(result1);
        System.out.println(result2);
        System.out.println(result3);
        System.out.println(result4);
    }


    public static void map2List() {

        Map<Integer, String> map = new HashMap<>();
        map.put(10, "apple");
        map.put(20, "orange");
        map.put(30, "banana");
        map.put(40, "watermelon");
        map.put(50, "dragonfruit");

        System.out.println("\n1. Export Map Key to List...");
        List<Integer> result = new ArrayList(map.keySet());
        result.forEach(System.out::println);

        System.out.println("\n2. Export Map Value to List...");
        List<String> result2 = new ArrayList(map.values());
        result2.forEach(System.out::println);

        System.out.println("\n");
        // split a map into 2 List
        List<Integer> resultSortedKey = new ArrayList<>();
        List<String> resultValues = map.entrySet().stream()
                //sort a Map by key and stored in resultSortedKey
                .sorted(Map.Entry.<Integer, String>comparingByKey().reversed())
                .peek(e -> resultSortedKey.add(e.getKey()))
                .map(x -> x.getValue())
                // filter banana and return it to resultValues
                .filter(x -> !"banana".equalsIgnoreCase(x))
                .collect(Collectors.toList());

        resultSortedKey.forEach(System.out::println);
        resultValues.forEach(System.out::println);
    }
    
}

运行结果:

Original...
{a=6, b=5, c=20, d=1, e=7, f=9, g=50, y=8, z=10, m=2, n=99}
Sorted...
{a=6, b=5, c=20, d=1, e=7, f=9, g=50, m=2, n=99, y=8, z=10}
{a=6, b=5, c=20, d=1, e=7, f=9, g=50, m=2, n=99, y=8, z=10}
{n=99, g=50, c=20, z=10, f=9, y=8, e=7, a=6, b=5, m=2, d=1}
{n=99, g=50, c=20, z=10, f=9, y=8, e=7, a=6, b=5, m=2, d=1}

1. Export Map Key to List...
50
20
40
10
30

2. Export Map Value to List...
dragonfruit
orange
watermelon
apple
banana


50
40
30
20
10
dragonfruit
watermelon
orange
apple

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值