List分組后獲取第一條數據


用戶實體

@Data
@AllArgsConstructor
public class User {
    private Integer id;
    private String name;
    private Integer score;
}

根據name分組,獲取每組最大分數對應的一條數據。

    public static void main(String[] args) {
        List<User> list=new ArrayList<>();
        list.add(new User(1,"kobe",20));
        list.add(new User(2,"james",40));
        list.add(new User(3,"durant",20));
        list.add(new User(4,"kyrie",30));
        list.add(new User(5,"paul",20));
        list.add(new User(6,"james",50));
        list.add(new User(7,"paul",40));
        list.add(new User(8,"james",30));
        list.add(new User(9,"paul",50));
        list.add(new User(10,"kyrie",55));
        list.add(new User(11,"james",60));
        list.add(new User(12,"kobe",70));
        list.add(new User(13,"wade",55));
        list.add(new User(14,"durant",59));
        list.add(new User(15,"kobe",45));
        list.add(new User(16,"kyrie",55));

       Map<String, User> collect = list.stream().sorted((u1, u2) -> u2.getScore() - u1.getScore()).collect(Collectors.groupingBy(User::getName, 
Collectors.collectingAndThen(Collectors.toList(), value -> value.get(0)))); ArrayList<User> users = new ArrayList<>(collect.values()); users.forEach(System.out::println); }

利用java8 的stream流來處理,先將score倒序,然后按name分組,然后選取第一條數據。

結果

 


免責聲明!

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



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