我有一些带有字段列表的模型对象 Account
,在简单的情况下有两个字段 String name
和 double margin
而且我需要得到这个账户的超过一定 margin 限制的确切页面,按 margin 和名称排序。每条记录都应以 margin 作为键,以 Account 作为值。
我制作了这个最小的代码示例,但似乎排序对我来说效果不佳。所以我将它包装在 TreeMap 中,但它会消耗额外的内存,我讨厌它。 可能应该等待在流内部修复此问题,并在边距相等的情况下按名称添加丢失的排序
@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));
}
}
最佳答案
您的问题和解决方案在某种程度上是矛盾的,一方面您显示的代码按 margin
对您的条目进行排序- 这是 double
;在这种情况下,有一种更简单的方法:
accounts.stream()
.filter(account -> account.getMargin() >= MARGIN_LIMIT)
.skip(PAGE_SIZE * (page - 1))
.limit(PAGE_SIZE)
.collect(Collectors.groupingBy(
Account::getMargin,
() -> new TreeMap<Double, List<Account>>(Comparator.reverseOrder()),
Collectors.toList()));
如果你想同时排序 margin
和 name
仍然保持定义为 Map<Double, List<Account>>
, 你将不得不坚持使用 LinkedHashMap
:
accounts.stream()
.filter(account -> account.getMargin() >= MARGIN_LIMIT)
.sorted(Comparator.comparingDouble(Account::getMargin)
.reversed()
.thenComparing(Comparator.comparing(Account::getName)))
.skip(PAGE_SIZE * (page - 1))
.limit(PAGE_SIZE)
.collect(Collectors.toMap(
Account::getMargin,
x -> {
List<Account> list = new ArrayList<>();
list.add(x);
return list;
},
(left, right) -> {
left.addAll(right);
return left;
},
LinkedHashMap::new));
关于java - 如何使用 java 8 流按几个条件获取排序的分页 map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47295643/