You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Pair的字符串键提取Map中对应行的全部值?

提取Map中特定行的所有值

嘿,你已经找对方向啦!既然能用Stream筛选出目标行的条目并完成求和,那要把这些值提取到数组或者集合里,只需要调整最后一步的操作就可以~

1. 提取到int数组

如果需要把值存入int[]类型的数组,把原来的sum()换成toArray()就行:

String targetKey = "你的目标字符串"; // 替换成你要查询的具体字符串
int[] rowValues = wordTopic.entrySet()
    .stream()
    .filter(entry -> entry.getKey().getKey().equals(targetKey))
    .mapToInt(Map.Entry::getValue)
    .toArray();

2. 提取到List集合

要是更习惯用集合存储(方便后续做增删、遍历等操作),可以用collect(Collectors.toList())来收集:

import java.util.stream.Collectors;

// ...

String targetKey = "你的目标字符串";
List<Integer> rowValuesList = wordTopic.entrySet()
    .stream()
    .filter(entry -> entry.getKey().getKey().equals(targetKey))
    .map(Map.Entry::getValue)
    .collect(Collectors.toList());

额外小技巧:保留列索引

如果你还需要同时获取Pair里的Integer(也就是矩阵的列索引),可以直接收集筛选后的Entry对象:

List<Map.Entry<Pair<String, Integer>, Integer>> fullRowEntries = wordTopic.entrySet()
    .stream()
    .filter(entry -> entry.getKey().getKey().equals(targetKey))
    .collect(Collectors.toList());

// 遍历获取列索引和对应值
for (var entry : fullRowEntries) {
    int columnIndex = entry.getKey().getValue();
    int value = entry.getValue();
    // 执行你需要的逻辑
}

这样就能轻松拿到目标行的所有元素啦!

内容的提问来源于stack exchange,提问作者Abdel-Rahman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:22:55