Java lambda list,map,轉換,過濾,去重操作


1、實體類

package com.lzk.test01.entity;

public class Person {
    private Long id;
    private String code;

    public Long getId() {
        return id;
    }

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

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getName() {
        return name;
    }

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

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    private String name;
    private String gender;
    private Integer age;
}

2、Java lambda list轉換map,以多個屬性作為key值

package com.lzk.test01.test;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class TestLaambdaMap {
    public static void main(String[] args) {
        List<Person> personList = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            Person person = new Person();
            person.setId((long) i);
            person.setName("張三" + i);
            person.setSex("");
            person.setAge(18);
            personList.add(person);
        }
        Map<String, Person> collect = personList.stream().collect(Collectors.toMap(person -> person.getId() + person.getName(), person -> person));
        System.out.println(collect);
    }
}

 3、list集合本身以某個屬性作為目標去重

 List<Person>  collect = personList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Person::getName))), ArrayList::new));

4、兩個list比對,取出交集

List<PersonCommon> commonList= Person1.stream().filter(item -> item.getName.equals(person2.getName())).collect(Collectors.toList());

5、兩個list比對,取出差集

List<PersonCommon> commonList= Person1.stream().filter(item -> !item.getName.equals(person2.getName())).collect(Collectors.toList());

 6、獲取list集合中單個屬性作為一個集合

List<String> courseIds=  users.stream().map(UserEntity::getUserName).collect(Collectors.toList());

 7、獲取list集合中多個屬性組成一個新的list集合(效率比較差)

List<A> collect = personList.stream().map(Person -> new A(Person.getId(), Person.getName())).collect(Collectors.toList());

使用lombok的@Builder注解
List<AppNameAddrDTO> collect = applicationList.stream().map(item -> AppNameAddrDTO.builder()
.appName(item.getAppName())
.appAddress(item.getAppAddress()).build()).collect(Collectors.toList());


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM