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

Java8中如何按HashMap值的字符串数组前两位元素分组并输出

你可以通过Java 8的Stream API结合Collectors.groupingBy实现需求,完整实现代码如下:

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class MapGroupDemo {
    public static void main(String[] args) {
        // 初始化示例Map
        Map<String,String[]> map = new HashMap<>();
        map.put("String1", new String[]{ "abc", "dfe", "new"});
        map.put("String8", new String[]{"xyz","hji","new"});
        map.put("String2", new String[]{"abc","dfe","old"});
        map.put("String3", new String[]{"abc","dfe","past"});
        map.put("String5", new String[]{"xyz","hji","ancient"});
        map.put("String6",new String[]{"xyz","hji","past"});
        map.put("String4", new String[]{"abc","dfe","ancient"});
        map.put("String7", new String[]{"xyz","hji","old"});

        // 按值数组前两个元素完成分组
        Map<List<String>, List<Map.Entry<String, String[]>>> groupedMap = map.entrySet().stream()
                // 增加校验避免空指针、数组越界,可根据业务场景调整
                .filter(entry -> entry.getValue() != null && entry.getValue().length >= 2)
                .collect(Collectors.groupingBy(entry -> Arrays.asList(entry.getValue()[0], entry.getValue()[1])));

        // 按示例格式排序输出
        map.entrySet().stream()
                .filter(entry -> entry.getValue() != null && entry.getValue().length >= 2)
                .sorted(Map.Entry.comparingByKey())
                .forEach(entry -> {
                    String valueFormat = Arrays.stream(entry.getValue())
                            .map(str -> "\"" + str + "\"")
                            .collect(Collectors.joining(","));
                    System.out.printf("%s:[{%s}]%n", entry.getKey(), valueFormat);
                });
    }
}

实现说明

  • 分组核心采用Collectors.groupingBy收集器,将值数组的前两个元素封装为List<String>作为分组键:因为Java中数组的equals()方法判断的是对象内存地址,无法按内容匹配,而List的equals()会逐元素比较内容,刚好满足按前两位值分组的要求。
  • 若你需要直接使用分组后的数据,直接使用代码中的groupedMap即可,其结构为Map<List<String>, List<Map.Entry<String, String[]>>>,对应“前两位元素组 -> 组内所有键值对”的映射关系。

内容的提问来源于stack exchange,提问作者Ashish Nijai

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.13 02:21:03