具有条件Math.abs(双精度)的HashMap流



请帮助我学习在地图之间导航。我有一个Map<字符串,列表>

sourceHashMapFind=.put("AAA", Arrays.asList(-5.6, 7.9, 5.7, 6.3));
sourceHashMapFind=.put("BBB", Arrays.asList(0.6, 5.8, 6.9, 8.0));
sourceHashMapFind=.put("CCC", Arrays.asList(0.5, 5.6, 6.9, 8.0));

并且我想要生成另一个==>哈希映射<字符串,双>

这是我的标准。如果0位置的绝对值大于1-->然后将Key和Value保存到新的queryPositions散列映射中。提前谢谢!

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class NewClass {
public static void main(String[] args) {
Map<String, List<Double>> sourceHashMapFind = new HashMap<>();
sourceHashMapFind.put("AAA", Arrays.asList(-5.6, 7.9, 5.7, 6.3));
sourceHashMapFind.put("BBB", Arrays.asList(0.6, 5.8, 6.9, 8.0));
sourceHashMapFind.put("CCC", Arrays.asList(0.5, 5.6, 6.9, 8.0));


HashMap<String, Double> queryPositions = sourceHashMapFind.entrySet()
.stream()
.sorted(Map.Entry.comparingByKey())
.filter(entry -> Math.abs(entry.getValue().get(0)) > 1.0)
.distinct()
.collect(Collectors.toMap(entry -> entry.getKey(), entry -> entry.getValue()));
}


}

这是运行输出

run:
Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - incompatible types: inference variable R has incompatible bounds
equality constraints: java.util.Map<K,U>
upper bounds: java.util.HashMap<java.lang.String,java.lang.Double>,java.lang.Object
at P2020_0928_stackOverflow_MyQuestion.NewClass.main(NewClass.java:21)
C:UsersUser1AppDataLocalNetBeansCache9.0executor-snippetsrun.xml:111: The following error occurred while executing this line:
C:UsersUser1AppDataLocalNetBeansCache9.0executor-snippetsrun.xml:94: Java returned: 1
BUILD FAILED (total time: 1 second)    

请看留言。谢谢你们!https://i.stack.imgur.com/iaK7j.jpg

您很接近,但对条目进行排序,然后收集到一个默认映射(HashMap(是没有意义的,该映射不保留插入顺序。另外,为什么要使用.distinct()

我会这样做:

Map<String, Double> queryPositions = sourceHashMapFind.entrySet().stream()
.filter(e -> Math.abs(e.getValue().get(0)) > 1.0)
.collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue().get(0)));

这假设您希望每个列表的第一项作为新映射的每个条目的值。

如果您需要按关键字排序的条目,您可能需要创建一个TreeMap:

Map<String, Double> queryPositions = sourceHashMapFind.entrySet().stream()
.filter(e -> Math.abs(e.getValue().get(0)) > 1.0)
.collect(Collectors.toMap(
e -> e.getKey(), 
e -> e.getValue().get(0),
(oldValue, newValue) -> newValue,
TreeMap::new)));

这将使用Collectors.toMap的重载版本,该版本需要映射的工厂。

最新更新