如何过滤具有特定条件的哈希图

How to filter a hashmap with specific conditions

我有以下初始哈希图:

纬度=[59, 48, 59, 12, 48]

经纬度=[41, 42, 46, 42]

EW=[W, W, W, W]

NS=[N, N, N, N]

LonM=[39, 23, 30, 48]

州=[俄亥俄州、南达科他州、西澳州、马萨诸塞州]

LatM=[5, 52, 35, 16]

城市=[扬斯敦、扬克顿、亚基马、伍斯特]

LonS=[0, 23, 36, 0]

伦敦=[80, 97, 120, 71]

我想使用具有以下调用的方法查询来过滤 Hashmap:

HashMap<Object, List<Object>> result = df.query( map -> "Youngstown".equals(df.getFrameInfo().get("City").get(0)))

函数的定义是:

`public HashMap<Object, List<Object>> query(Predicate<Object> cond){

    HashMap<Object, List<Object>> ref = new HashMap<>(frameInfo);

        Map<Object, List<Object>> result = ref.entrySet()
                .stream()
                .filter(cond)
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

        System.out.println("Result: " + result);`

但最困难的部分是通过特定方式获取hashmap结果。我只想将城市的列作为参数传递。

例如:如果我使用这个参数:

HashMap<Object, List<Object>> result = df.query( map -> "Youngstown".equals(df.getFrameInfo().get("City").get(0)))

输出应该是:

LatS=[59]
LatD=[41]
EW=[W]
NS=[N]
LonM=[N]
State=[OH]
LatM=[5]
City=[Youngstown]
LonS=[0]
Lond=[80]

非常感谢你!

问题

首先,致电:

df.query(map -> "Youngstown".equals(df.getFrameInfo().get("City").get(0)))

确实没有意义,因为在您的特定情况下,前提是谓词始终评估为 true - 然后您将其传递给 filter()。 请注意,您根本没有使用谓词的 map 变量。

可能的解决方案

我建议向 query 方法添加额外的参数,表示我们正在查询的“键”(假设我们想始终查询单个键)。

然后,为值传递谓词,它将在列表中找到特定“键”的值。

我们将获取找到的值的索引,然后通过提取该索引上所有键的值来构造最终 Map

public Map<Object, List<Object>> query(String keySelector, Predicate<Object> valuePredicate) {
    final List<Object> row = frameInfo.get(keySelector);
    final List<Integer> indices = getColumnIndex(row, valuePredicate);

    return getColumnMap(indices);
}

private List<Integer> getColumnIndex(List<Object> row, Predicate<Object> valuePredicate) {
    return IntStream.range(0, row.size()).filter(columnIndex -> valuePredicate.test(row.get(columnIndex))).boxed().collect(Collectors.toList());
}

private Map<Object, List<Object>> getColumnMap(List<Integer> columnIndices) {
    final Map<Object, List<Object>> result = new HashMap<>();
    for (Map.Entry<Object, List<Object>> entry : frameInfo.entrySet()) {
        for (int columnIndex : columnIndices) {
            result.putIfAbsent(entry.getKey(), new ArrayList<>());
            result.get(entry.getKey()).add(entry.getValue().get(columnIndex));
        }
    }
    return result;
}

// Example call
final Map<Object, List<Object>> result = df.query("City", "Youngstown"::equals);
System.out.println(result);