java8 lambda-list转map、过滤、求和、分组等

java8中开始引入了lambda表达式,该表达式大大简化了代码量,使用lambda处理list列表很方便,下面介绍一些常用的使用方式

数据对象:

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Objects;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * 人类
 * @create 2018-10-17 12:40
 **/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Person implements Serializable {
    private static final long serialVersionUID = -3236552889204227101L;
    private Integer id;
    private Integer age;
    private String name;
    private BigDecimal money;

    public Person(Integer id, String name) {
        this.id = id;
        this.name = name;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Person person = (Person) o;
        return Objects.equals(id, person.id) &&
                Objects.equals(name, person.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id, name);
    }
}

list中添加对象列表:

Person p1 = new Person(1,10,"zs",new BigDecimal(10.11).setScale(2, BigDecimal.ROUND_HALF_UP));
        Person p2 = new Person(2,11,"zs2",new BigDecimal(5.52).setScale(2, BigDecimal.ROUND_HALF_UP));
        Person p3 = new Person(3,15,"zs",new BigDecimal(6.29).setScale(2, BigDecimal.ROUND_HALF_UP));

        List personList = new ArrayList<>(3);
        personList.add(p1);
        personList.add(p2);
        personList.add(p3);

1、过滤

List personFilterList = personList.stream().filter(person -> "zs".equals(person.getName())).collect(Collectors.toList());
        System.out.println(personFilterList);

运行结果:[Person(id=1, age=10, name=zs, money=10.11), Person(id=3, age=15, name=zs, money=6.29)]

2、计算总数(sum)

Long totalAges = personList.stream().mapToLong(Person::getAge).sum();
        System.out.println("totalAges:" + totalAges);

运行结果:totalAges:36

3、对象属性转换成list

List ids = personList.stream().map(Person::getId).collect(Collectors.toList());
        System.out.println("ids:" + ids);
运行结果:ids:[1, 2, 3]

4、分组

Map> personGroupMap = personList.stream().collect(Collectors.groupingBy(Person::getName));
        System.out.println("personGroupMap:" + personGroupMap);

运行结果:personGroupMap:{zs2=[Person(id=2, age=11, name=zs2, money=5.52)], zs=[Person(id=1, age=10, name=zs, money=10.11), Person(id=3, age=15, name=zs, money=6.29)]}

5、计算BigDecial类型数据和

BigDecimal totalMoney = personList.stream().map(Person::getMoney).reduce(BigDecimal.ZERO, BigDecimal::add);
        System.out.println("totalMoney:" + totalMoney);

运行结果:totalMoney:21.92

6、list转成map,不允许有重复key,存在重复key时会报错

Map personMap = personList.stream().collect(Collectors.toMap(Person::getId, Function.identity()));
        personMap.forEach((k,v) -> System.out.println("key:" + k + ", value=" + v));

运行结果:

key:1, value=Person(id=1, age=10, name=zs, money=10.11)
key:2, value=Person(id=2, age=11, name=zs2, money=5.52)
key:3, value=Person(id=3, age=15, name=zs, money=6.29)

7、list转成map,存在重复key时自己决定怎么样处理

Person p1 = new Person(1,10,"zs",new BigDecimal(10.11).setScale(2, BigDecimal.ROUND_HALF_UP));
        Person p2 = new Person(1,11,"zs2",new BigDecimal(5.52).setScale(2, BigDecimal.ROUND_HALF_UP));
        Person p3 = new Person(3,15,"zs",new BigDecimal(6.29).setScale(2, BigDecimal.ROUND_HALF_UP));

        List personList = new ArrayList<>(3);
        personList.add(p1);
        personList.add(p2);
        personList.add(p3);

// list 转成map,重复key处理,k1,k2 重复时取k2,即采用后者覆盖前者的方式
        Map duplicateKeyMap = personList.stream().collect(Collectors.toMap(Person::getId, Function.identity(), (k1, k2) -> k2));
        duplicateKeyMap.forEach((k,v) -> System.out.println("key:" + k + ", value=" + v));

运行结果:

key:1, value=Person(id=1, age=11, name=zs2, money=5.52)
key:3, value=Person(id=3, age=15, name=zs, money=6.29)

完成测试类代码:

import com.springboot.demo.copy.Person;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.junit.Test;

/**
 * 测试类
 *
 * @date 2019-04-03 14:44
 **/
public class LambdaTest {
    @Test
    public void test(){
        Person p1 = new Person(1,10,"zs",new BigDecimal(10.11).setScale(2, BigDecimal.ROUND_HALF_UP));
        Person p2 = new Person(2,11,"zs2",new BigDecimal(5.52).setScale(2, BigDecimal.ROUND_HALF_UP));
        Person p3 = new Person(3,15,"zs",new BigDecimal(6.29).setScale(2, BigDecimal.ROUND_HALF_UP));

        List personList = new ArrayList<>(3);
        personList.add(p1);
        personList.add(p2);
        personList.add(p3);

        // 过滤
        List personFilterList = personList.stream().filter(person -> "zs".equals(person.getName())).collect(Collectors.toList());
        System.out.println(personFilterList);

        // 计算总数
        Long totalAges = personList.stream().mapToLong(Person::getAge).sum();
        System.out.println("totalAges:" + totalAges);


        // list 转成map, 重复key会报错
        Map personMap = personList.stream().collect(Collectors.toMap(Person::getId, Function.identity()));
        personMap.forEach((k,v) -> System.out.println("key:" + k + ", value=" + v));

        // list 转成map,重复key处理,k1,k2 重复时取k2,即采用后者覆盖前者的方式
        /*Map duplicateKeyMap = personList.stream().collect(Collectors.toMap(Person::getId, Function.identity(), (k1, k2) -> k2));
        duplicateKeyMap.forEach((k,v) -> System.out.println("key:" + k + ", value=" + v));*/

        // 对象属性转成list
        List ids = personList.stream().map(Person::getId).collect(Collectors.toList());
        System.out.println("ids:" + ids);

        // 分组
        Map> personGroupMap = personList.stream().collect(Collectors.groupingBy(Person::getName));
        System.out.println("personGroupMap:" + personGroupMap);

        // 计算BigDecial类型数据和
        BigDecimal totalMoney = personList.stream().map(Person::getMoney).reduce(BigDecimal.ZERO, BigDecimal::add);
        System.out.println("totalMoney:" + totalMoney);

    }
}

 

你可能感兴趣的:(java基础知识)