1. 程式人生 > >java8對list按條件分組

java8對list按條件分組

建立一個UserInfo`

package com.example.demo.a;

public class UserInfo {
    private String id;
    private String name;
    public UserInfo(String id, String name) {
        this.id = id;
        this.name = name;
    }

    public String getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
package com.example.demo.a;

import com.alibaba.fastjson.JSON;
import org.junit.Test;

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

public class Test1 {
    @Test
    public void test2() {
        List<UserInfo> appleList = new ArrayList<>();
        appleList.add(new UserInfo("2", "zhangsan1"));
        appleList.add(new UserInfo("8", "zhangsan2"));
        appleList.add(new UserInfo("4", "zhangsan3"));
        appleList.add(new UserInfo("6", "zhangsan4"));
        Map<String, List<UserInfo>> groupBy = 
        appleList.stream().collect(Collectors.groupingBy(UserInfo::getId));
        System.out.println(JSON.toJSONString(groupBy));
    }
}