gpt4 book ai didi

java - 转换 map 值

转载 作者:行者123 更新时间:2023-12-02 01:10:58 24 4
gpt4 key购买 nike

以下问题:

我有一张 map Map<A, List<Integer> map我想将其转换为 Map<A, Double> ,使用流。为了转换它,使用以下技术:您将该列表中的每个元素与下一个元素相减(最后一个元素与第一个元素相减),将正结果和负结果分组(0 将被忽略),获取两组的平均值( double )并返回绝对和两个平均值均为双倍(这将是结果 map 的关键)。

例如,您有 map :

A = 30, 40, 50; //here the result would be (A = 30) because 30 - 40 = -10; 40 - 50 = -10; 50 - 30 = 20;
//that means you calculate average of (-10, -10), which is -10 and average of (20), which is 20
//at last you get the absolute sum of those two averages (10 + 20 = 30)

A1 = 40, 70, 100, 30; //resulting in (A1 = 93.33333) because average of (-10, -30, -30) is -23.333 and average of (70) is 70

A2 = 100, 100, 110, 120; //resulting in (A2 = 30) because average of (-10, 10) = -10 and average of (20) = 20.
//The zero here (100-100 = 0) will not be regarded

所以最后你得到了 map {A = 30, A1 = 83.33333, A2 = 30)。

我现在的问题是我不知道如何计算列表中每个元素之间的差异并对它们进行分组。

最佳答案

在这样做的过程中,我相信我发现您的答案之一是不正确的。总和应为 93.333333。

当您说忽略 0 时,这意味着如果差异为 0,则要平均的项目数不会增加。

这是完整的流答案。需要注意的是,它需要 Java 12+ 才能使用 Collectors.teeing()

给出以下值图。

      Map<String, List<Integer>> map = Map.of("A",
List.of(30, 40, 50),
"A1",
List.of(40, 70, 100, 30),
"A2",
List.of(100, 100, 110, 120));

生成的 map 在此处计算。

      Map<String, Double> result =
map.entrySet().stream().collect(Collectors.toMap(Entry::getKey,

从这里开始的所有内容都会计算最终映射条目的 double 值。

     e -> IntStream.range(0,
e.getValue().size()).mapToDouble(
n -> e.getValue().get(n % e.getValue().size())- e.getValue().get((n + 1)
% e.getValue().size()))
.boxed().collect(Collectors.teeing(Collectors.filtering((n -> n < 0),
Collectors.averagingDouble(a -> a)),
Collectors.filtering((n -> n > 0),
Collectors.averagingDouble(a -> a)),
(a, b) -> Math.abs(a)+ Math.abs(b)))));

System.out.println(result);
  1. entrySet().stream 用于从源映射中获取原始数据。
  2. e.getValue() 是列表,用于通过 get() 获取列表的大小和各个值
  3. 根据您的要求使用余数运算符减去这些值。这允许从列表中的最后一个条目中减去第一个条目。
  4. 这些差异中的每一个都通过teeing()方法发送到两个不同的收集器。第一个收集器对小于 0 的值进行过滤和平均值。第二个收集器对大于 0 的值执行相同的操作。
  5. 然后将这两个收集器的结果作为绝对和相加,从而得到结果 map 的 double 值。

关于java - 转换 map 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59417220/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com