如何通过列表中的复杂逻辑获得价值 [英] how can i get value through complex logic from list
问题描述
我有过滤 personCountFilter = 3
,并且列表如下:
I have filter personCountFilter=3
, and have list as below:
Rate{ PersonCount:1, LOS:1}
Rate{ PersonCount:1, LOS:2}
Rate{ PersonCount:1, LOS:3}
Rate{ PersonCount:2, LOS:1}
Rate{ PersonCount:2, LOS:2}
Rate{ PersonCount:2, LOS:3}
Rate{ PersonCount:3, LOS:2}
Rate{ PersonCount:3, LOS:4}
Rate{ PersonCount:3, LOS:5}
Rate{ PersonCount:3, LOS:6}
Rate{ PersonCount:4, LOS:3}
Rate{ PersonCount:5, LOS:7}
Rate{ PersonCount:6, LOS:7}
过滤后我的预期:
Rate{ PersonCount:2, LOS:1}
Rate{ PersonCount:3, LOS:2}
Rate{ PersonCount:4, LOS:3}
Rate{ PersonCount:3, LOS:4}
Rate{ PersonCount:3, LOS:5}
Rate{ PersonCount:3, LOS:6}
Rate{ PersonCount:5, LOS:7}
如何在按LOS分组后得到值,如果personCount匹配过滤器获得此值,如果不匹配,则最接近 personCountFilter
,更大 personCountFilter
第一次
how can I get value after grouping by LOS, and if personCount matched filter get this one, if not matched, get closest to personCountFilter
, bigger personCountFilter
first
我试图使用
HashSet<Rate> testSet = rates.stream()
.collect(Collectors.collectingAndThen(
Collectors.toMap(Rate::getLengthOfStayCount,
Function.identity(),
(previous, current) ->
{
return previous.getPersonCount() >
current.getPersonCount() ? previous : current;
}),
map ->
{
HashSet<Rate> set = new HashSet<>();
set.addAll(map.values());
return set;
}));
但它返回
Rate{ PersonCount:2, LOS:1}
Rate{ PersonCount:3, LOS:2}
Rate{ PersonCount:4, LOS:3}
Rate{ PersonCount:3, LOS:4}
Rate{ PersonCount:3, LOS:5}
Rate{ PersonCount:3, LOS:6}
Rate{ PersonCount:6, LOS:7}
当按LOS分组后,当前获得最大人数。
Current it gets max personCount when after grouping by LOS
推荐答案
如果我理解正确,你想得到每个组的元素,它具有最近的 personCount
属性数字 3
,如果出现平局,则优先选择较高的数字。
If I understand you correctly, you want to get the element of each group, which has the personCount
property closest to the number 3
, with preference to the higher number in case of a tie.
您可以使用
HashSet<Rate> testSet = rates.stream()
.collect(Collectors.collectingAndThen(
Collectors.toMap(Rate::getLengthOfStayCount,
Function.identity(),
BinaryOperator.minBy(
Comparator.comparingDouble(rate -> Math.abs(rate.getPersonCount()-3.1)))
),
map -> new HashSet<>(map.values())
));
Math.abs(rate.getPersonCount() - 3)
是您的目标号 3
的距离,获得具有该值的最小值的元素将获得最接近的值。通过简单地使用 3.1
而不是 3
,我们在平局的情况下获得更高的数字(假设你属性)有一个整数类型)。
Math.abs(rate.getPersonCount()-3)
is the distance to your goal number 3
, getting the element with the minimum of that value will get the closest. By simply using 3.1
instead of 3
, we achieve preference to higher numbers in case of a tie (assuming that you property has an integer type).
这篇关于如何通过列表中的复杂逻辑获得价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!