要根据用户属性相同的次数最多来排序 Java List,可以使用 Stream API 来实现。

假设有一个 User 类,包含属性 id 和属性 name,现在有一个 List<User> userList,我们要根据 name 属性相同的次数最多来排序。

首先,我们可以使用 Collectors.groupingBy() 方法来按照 name 属性进行分组,然后使用 Collectors.counting() 方法来统计每个 name 属性的出现次数。最后,使用 Stream 的 sorted() 方法来根据出现次数进行排序。

下面是具体的代码实现:

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

public class Main {
    public static void main(String[] args) {
        List<User> userList = List.of(
                new User(1, "Alice"),
                new User(2, "Bob"),
                new User(3, "Alice"),
                new User(4, "Bob"),
                new User(5, "Charlie"),
                new User(6, "Alice")
        );

        List<User> sortedList = userList.stream()
                .collect(Collectors.groupingBy(User::getName, Collectors.counting()))
                .entrySet().stream()
                .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
                .flatMap(entry -> userList.stream().filter(user -> user.getName().equals(entry.getKey())))
                .collect(Collectors.toList());

        sortedList.forEach(System.out::println);
    }
}

class User {
    private int id;
    private String name;

    public User(int id, String name) {
        this.id = id;
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + ''' +
                '}';
    }
}

输出结果为:

User{id=1, name='Alice'}
User{id=3, name='Alice'}
User{id=6, name='Alice'}
User{id=2, name='Bob'}
User{id=4, name='Bob'}
User{id=5, name='Charlie'}

可以看到,根据 name 属性相同的次数最多来排序后,出现次数最多的是 name 为"Alice" 的用户。

Java 使用 Stream API 对 List 进行排序 - 根据用户属性出现次数最多

原文地址: https://www.cveoy.top/t/topic/eXQ 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录