具有条件 Math.abs(double) 的 HashMap 流

HashMap stream with criteria Math.abs(double)

请帮助我学习在地图之间导航。我有一个 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));

我想生成另一个映射 ==> HashMap

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

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_Whosebug_MyQuestion.NewClass.main(NewClass.java:21)
C:\Users\User1\AppData\Local\NetBeans\Cache.0\executor-snippets\run.xml:111: The following error occurred while executing this line:
C:\Users\User1\AppData\Local\NetBeans\Cache.0\executor-snippets\run.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 的重载版本。