简体   繁体   中英

Sorting the List after Sorting the Key

So I need to get a List<Expense> by a user, but that is ordered by descending Value of Expense. The method of Expense to get the Value is getValue . At the moment I'm only getting all the Expenses by each user, now I just need to order it. What I have is this:

public List<Expense> getListFactIndivValor() {
    TreeMap<String, List<Expense>> map = new TreeMap<>();
    Company c = new Company();
    for ( Expense e : c.getExpenses()) { 
        List<Expense> expenses = map.get(e.getTINUser());
        if (expenses == null) {
            expenses = new ArrayList<>();
            map.put(e.getTINUser(), expenses);
        }
        expenses.add(e);
     }

    List<Expense> result = new ArrayList<>();
    for (String s : map.descendingKeySet()) {
        List<Expense> expenses = map.get(s);
        for ( Expense expense : expenses ) {
            result.add( expense);
        }
    }
    return result;
}

You can sort your Expense by two properties at once, no need to populate TreeMap . This is kinda waste.

Try this:

public List<Expense> getListFactIndivValor() {
    List<Expense> expense = c.getExpenses();
    Collections.sort(expense, Comparator.comparing(Expense::getTinUser)
                                     .thenComparing(Expense::getValue));
    return expense;
}

Expense needs to implement Comparable . You'll then need to sort the list at the bottom of your method before your return statement, like:

expenses.sort(Comparator.comparing(Expense::getValue));

Hope that helps!

You need to sort the expenses list using a Comparator.

After you finish populating the treeMap (I'm not sure why you need a treemap here), you can do

return map.entrySet()
           .stream()
           .flatMap(entry -> entry.getValue().stream())
           .collect(Collectors.collectingAndThen(Collectors.toList(), result -> result.stream()
                   .sorted(Comparator.comparingInt(Expense::getValue).reversed())
                    .collect(Collectors.toList())));

It streams the entries of the map and flatMaps it since the value is a list and collects it into a list (as you do using the last for loop). Then it sorts the list using the passed Comparator which sorts the list in reversed order ( reversed() ) and again collects the result into a list.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM