0

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.

  • 2
    Welcome to StackOverflow! What have you tried so far? – ETO Dec 20 '18 at 08:29
  • I was trying to use Collections.sort() but it doesn't take user defined criteria. –  Dec 20 '18 at 08:30
  • @Aman Please elaborate your question by adding your code. https://stackoverflow.com/help/how-to-ask – ETO Dec 20 '18 at 08:32
  • Comparator can be help here – bananas Dec 20 '18 at 08:37
  • To sort by "number of occurences" of something, you need to count occurences first. Note that there are multiple ways to sort using custom comparators you could use once you have determined the counts: https://stackoverflow.com/questions/2784514/sort-arraylist-of-custom-objects-by-property – Hulk Dec 20 '18 at 08:39
  • 1
    @Aman Can you add more source code and also what your expected list will look like? – medkhelifi Dec 20 '18 at 08:39
  • @medKHELIFI check out the output i expected. edited the question –  Dec 20 '18 at 08:57

2 Answers2

1

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.

Roi
  • 983
  • 9
  • 17
  • can you check out the question again please, i have edited it may clear what i want. –  Dec 20 '18 at 11:51
0

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);
Sachin
  • 176
  • 1
  • 11