JavaList對象集合按對象屬性分組,分組彙總,過濾等操作(java筆記)

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

<code>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>> collect = list.stream().collect(Collectors.groupingBy(PersonData::getType));
System.out.println(collect);

//根據某個屬性分組,彙總某個屬性
Map<string> 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);
}
}

/<string>/<string>/<string>/<persondata>/<persondata>/<code>

結果輸出:

{用戶=[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[張三, 李四, 王五]

<code>
public class PersonData {
\tprivate String id;
\tprivate String type;
\tprivate String name;
\tprivate int age;

\tpublic String getId() {
\t\treturn id;
\t}

\tpublic void setId(String id) {
\t\tthis.id = id;
\t}

\tpublic String getType() {
\t\treturn type;
\t}

\tpublic void setType(String type) {
\t\tthis.type = type;
\t}

\tpublic String getName() {
\t\treturn name;
\t}

\tpublic void setName(String name) {
\t\tthis.name = name;
\t}

\tpublic int getAge() {
\t\treturn age;
\t}

\tpublic void setAge(int age) {
\t\tthis.age = age;
\t}

\tpublic PersonData(String id, String type, String name, int age) {
\t\tsuper();
\t\tthis.id = id;
\t\tthis.type = type;
\t\tthis.name = name;
\t\tthis.age = age;
\t}

\tpublic PersonData() {

\t}
}/<code>


分享到:


相關文章: