user10796473
user10796473

Reputation:

How to sort list of user defined criteria in java collections

I want to sort the below item according to number of occurrences

I am using

List<Gender> list = query.list();
Set<Gender> unique = new HashSet<Gender>(list);
        for (Gender key : unique) {
            System.out.println(key + ": " + Collections.frequency(list, key));
        }

But above logic is giving the same sequence as frequency is counted based on complete list not based on AssignedTo. I want to find frequency and then sort the list based on frequency.

And all these info are stored in list now.

Upvotes: 0

Views: 262

Answers (2)

Sachin
Sachin

Reputation: 176

you can try and tweak the below sample program to first find frequency and then populate list according to sorted linkedHashMap.

    List<Gender> list = new ArrayList<>();
    list.add(Gender.FEMALE);
    list.add(Gender.MALE);
    list.add(Gender.MALE);
    list.add(Gender.FEMALE);
    list.add(Gender.MALE);
    list.add(Gender.FEMALE);

    list.add(Gender.MALE);
    Map<Gender,Long> frequency2 = list.stream().collect(
            Collectors.groupingBy(Function.identity(),Collectors.counting())
    ).entrySet().stream().sorted(Map.Entry.comparingByValue()).collect(
            (Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
                    (oldValue, newValue) -> oldValue, LinkedHashMap::new)));

    List<Gender> result = new ArrayList<>();
    for (Map.Entry<Gender,Long> entry: frequency2.entrySet()) {
        for (int i = 0; i < entry.getValue(); i++) {
            result.add(entry.getKey());
        }
    }
    System.out.println(result);

Upvotes: 0

Roi
Roi

Reputation: 1003

If you are querying this from an SQL database, you can make count of AssignedTo and use group by, and then return them in a descending order.

If this is just in Java, then use a loop to go over the list, and make a count for each AssignedTo.

Upvotes: 1

Related Questions