Java List對象集合按對象屬性分組、分組匯總、過濾等操作示例


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

public class Test {
    public static void main(String[] args){
        List<PersonData> list = new ArrayList<PersonData>();
        PersonData p1 = new PersonData();
        p1.setId("1");
        p1.setName("張三");
        p1.setType("管理員");
        p1.setAge(20);
        list.add(p1);

        PersonData p2 = new PersonData();
        p2.setId("2");
        p2.setName("李四");
        p2.setType("管理員");
        p2.setAge(30);
        list.add(p2);

        PersonData p3 = new PersonData();
        p3.setId("3");
        p3.setName("王五");
        p3.setType("用戶");
        p3.setAge(40);
        list.add(p3);

        PersonData p4 = new PersonData();
        p4.setId("4");
        p4.setName("馬六");
        p4.setType("訪客");
        p4.setAge(50);
        list.add(p4);

        //跟據某個屬性分組
        Map<String, List<PersonData>> collect = list.stream().collect(Collectors.groupingBy(PersonData::getType));
        System.out.println(collect);
        
        //根據某個屬性分組,匯總某個屬性
        Map<String, Integer> collect2 = list.stream().collect(Collectors.groupingBy(PersonData::getType,Collectors.summingInt(PersonData::getAge)));
        System.out.println(collect2);
        
        //根據某個屬性添加條件過濾數據,
        list = list.stream().filter(u -> !u.getType().equals("訪客")).collect(Collectors.toList());
        System.out.println(list);
        
        //判斷一組對象里面有沒有屬性值是某個值
        boolean add = list.stream().anyMatch(m -> "王五".equals(m.getName()));
        System.out.println(add);
        
        //取出一組對象的某個屬性組成一個新集合
        List<String> names=list.stream().map(PersonData::getName).collect(Collectors.toList());
        System.out.println(names);
    }
}

結果輸出:

{用戶=[com.test4.PersonData@19a45b3], 訪客=[com.test4.PersonData@99a589], 管理員=[com.test4.PersonData@372a00, com.test4.PersonData@dd8dc3]}
{用戶=40, 訪客=50, 管理員=50}
[com.test4.PersonData@372a00, com.test4.PersonData@dd8dc3, com.test4.PersonData@19a45b3]
true
[張三, 李四, 王五]


public class PersonData {
	private String id;
	private String type;
	private String name;
	private int age;

	public String getId() {
		return id;
	}

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

	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}

	public String getName() {
		return name;
	}

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

	public int getAge() {
		return age;
	}

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

	public PersonData(String id, String type, String name, int age) {
		super();
		this.id = id;
		this.type = type;
		this.name = name;
		this.age = age;
	}

	public PersonData() {

	}
}


免責聲明!

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



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