Java 8拆分字符串并在Map中创建Map [英] Java 8 Split String and Create Map inside Map

查看:175
本文介绍了Java 8拆分字符串并在Map中创建Map的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像101-1-5,101-2-4,102-1-5,102-2-5,102-3-5,103-1-4这样的字符串.

I have a String like 101-1-5,101-2-4,102-1-5,102-2-5,102-3-5,103-1-4.

我要将其添加到Map<String, Map<String, String>>.

赞:{101={1=5, 2=4}, 102={1=5, 2=5, 3=5}, 103={1=4}}

如何使用Java 8流执行此操作?

How to do this using Java 8 stream?

我尝试使用普通的Java.而且效果很好.

I tried using normal Java. And it works fine.

public class Util {
    public static void main(String[] args) {

        String samp = "101-1-5,101-2-4,102-1-5,102-2-5,102-3-5,103-1-4";

        Map<String, Map<String, String>> m1 = new HashMap<>();
        Map<String, String> m2 = null;

        String[] items = samp.split(",");

        for(int i=0; i<items.length; i++) {
            String[] subitem = items[i].split("-");
            if(!m1.containsKey(subitem[0]) || m2==null) {
                m2 = new HashMap<>();
            }
            m2.put(subitem[1], subitem[2]);
            m1.put(subitem[0], m2);
        }
        System.out.println(m1);
    }
}

推荐答案

您可以为此使用以下代码段:

You can use the following snippet for this:

Map<String, Map<String, String>> result = Arrays.stream(samp.split(","))
        .map(i -> i.split("-"))
        .collect(Collectors.groupingBy(a -> a[0], Collectors.toMap(a -> a[1], a -> a[2])));

首先,它会创建您的项目流,这些项目将映射到包含子项的数组流.最后,通过在第一个子项目上使用group by收集所有内容,并创建一个内部地图,其中第二个值为键,最后一个为值.

First it creates a Stream of your items, which are mapped to a stream of arrays, containing the subitems. At the end you collect all by using group by on the first subitem and create an inner map with the second value as key and the last one as value.

结果是:

{101={1=5, 2=4}, 102={1=5, 2=5, 3=5}, 103={1=4}}

这篇关于Java 8拆分字符串并在Map中创建Map的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆