java8 list to map , map to String

原创
2020/10/30 15:55
阅读数 1.2K
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class Test7 {

    public static void main(String[] args) {

        List<User> list = new ArrayList<>();


        User user14 = new User();
        user14.setName("小红1");
        user14.setAge(14);
        list.add(user14);

        User user1 = new User();
        user1.setName("小明");
        user1.setAge(1);
        list.add(user1);

        User user2 = new User();
        user2.setName("小明");
        user2.setAge(2);
        list.add(user2);


        User user3 = new User();
        user3.setName("小明");
        user3.setAge(3);
        list.add(user3);


        User user4 = new User();
        user4.setName("小明");
        user4.setAge(4);
        list.add(user4);


        User user11 = new User();
        user11.setName("小红");
        user11.setAge(11);
        list.add(user11);


        User user12 = new User();
        user12.setName("小明");
        user12.setAge(1);
        list.add(user12);


        User user13 = new User();
        user13.setName("小红");
        user13.setAge(13);
        list.add(user13);

        Map<String, Long> map = list.stream().collect(Collectors.groupingBy(User::getName, Collectors.counting()));

        map.forEach((k, v) -> {
            System.out.println("k --> " + k + ", v --->" + v);
        });

        String s = map.entrySet().stream().map(e -> e.getKey() + " * " + e.getValue()).sorted().collect(Collectors.joining(","));
        System.out.println(s);

    }


}

class User {

    private String name;
    private int age;


    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;
    }
}

结果

k --> 小明, v --->5
k --> 小红1, v --->1
k --> 小红, v --->2
小明 * 5,小红 * 2,小红1 * 1

展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部