I have some model object Account with list of fields, in simple case with two fields String name and double margin
And I need to get exact page of this accounts which is over some margin limit, sorted by margin & name. Each record should have margin as key, and Account as value.
I made this minimal example of code, but seems like sorting doesn't works well for me. So I wrap it in TreeMap, but it will cost extra memory and I hate it. Probably should be wait to fix this inside of streams and add losted sort by name in case of equals margin
@Data
class Account {
private final String name;
private final double margin;
private final static double MARGIN_LIMIT = 100;
private final static int PAGE_SIZE = 3;
private static Set<Account> accounts = new HashSet<>();
public static void main(String[] args) {
accounts.add(new Account("user1", 200));
accounts.add(new Account("user2", 100));
accounts.add(new Account("user3", 150));
accounts.add(new Account("user4", 175));
accounts.add(new Account("user5", 75));
accounts.add(new Account("user6", 110));
Map<Double,Account> val = new TreeMap<Double,Account>(Comparator.reverseOrder());
val.putAll(getClientsForClosing(2));
System.out.println(val);
}
private static Map<Double, Account> getClientsForClosing(int page) {
return accounts.stream()
.filter(account -> account.getMargin() >= MARGIN_LIMIT)
.sorted(Comparator.comparingDouble(Account::getMargin).reversed())
.skip(PAGE_SIZE * (page - 1))
.limit(PAGE_SIZE)
.collect(Collectors.toMap(Account::getMargin, o -> o));
}
}