![](/img/trans.png)
[英]what is the best way to compare two complex java object and generate event depending upon comparision
[英]What is the best way to compare two possible set of values of the same object in Java?
讓我詳細說明一下這個問題。 我有一組對象說,A,B,C 等,我有一組場景說,case1,case2 和 case3 等,基於這些對象的值可以改變。 找到為 object 提供最佳值的方案的最佳方法是什么?
我目前的做法如下:
實現 Case1 的條件並將對象的值存儲在 Map<object, ArrayList> 中
實現 Case2 的條件並將對象的值存儲在第二個 Map<object, ArrayList> 等中。
然后比較每個 map 中的值列表
Case1: ArrayList<Double> array1 = {1,2,3}; ArrayList<Doubel> array2 = {3,4,5}; myMatrix1.put('A',array1) myMatrix1.put('B',array2); totMatrix.put(myMatrix1,18); //sum of all elements in the two lists Case2: ArrayList<Double> array3 = {9,10,11}; ArrayList<Double> array4 = {12,10,1}; myMatrix2.put('A',array3); myMatrix2.put('B',array4); totMatrix.put(myMatrix2,53);
然后我需要將兩個矩陣中兩個數組列表的值相加,並找到給出最高值的那個。 例如,上面示例中的 case2 為我的對象集提供了最佳值。
現在的挑戰是,隨着場景數量的增加,我最終會創建一些我認為必須避免的此類地圖。 如何最好地實現這一目標?
將不勝感激任何相同的方向! 非常感謝!
您可以使用stream
:
public static Map<Character, List<Double>> highestValues(Map<Character, List<Double>>... matrices) {
return Arrays.stream(matrices).collect(
Collectors.toMap(matrix -> sumValues(matrix),
Function.identity(), (m1, m2) -> m1, TreeMap::new))
.lastEntry().getValue();
}
public static double sumValues(Map<?, List<Double>> matrix) {
return matrix.values().stream().flatMap(List::stream)
.mapToDouble(Double::doubleValue).sum();
}
然后:
Map<Character, List<Double>> matrix1 = Map.of(
'A', List.of(1d, 2d, 3d),
'B', List.of(3d, 4d, 5d));
Map<Character, List<Double>> matrix2 = Map.of(
'A', List.of(9d, 10d, 11d),
'B', List.of(12d, 10d, 1d));
System.out.println(highestValues(matrix1, matrix2));
Output:
{A=[9.0, 10.0, 11.0], B=[12.0, 10.0, 1.0]}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.