Java8 Lamda String To Map

import java.util.Arrays;
import java.util.stream.Collectors;

public class StringToMap {

    public static void main(String[] args) {

        try {
            String str = "SALES:0,SALE_PRODUCTS:1,EXPENSES:2,EXPENSES_ITEMS:3";

            Arrays.asList(str.split(",")).stream().map(s -> s.split(":"))
                    .collect(Collectors.toMap(e -> e[0], e -> e[1])).forEach((key, value) -> {
                        System.out.println("key = " + key + ",value = " + value);
                    });

            System.out.println();

            Arrays.asList(str.split(",")).stream().map(s -> s.split(":"))
                    .collect(Collectors.toMap(e -> e[0], e -> Integer.parseInt(e[1]))).forEach((key, value) -> {
                        System.out.println("key = " + key + ",value + 10 = " + (value + 10));
                    });
            System.out.println();

            System.out.println(Arrays.asList(str.split(",")).stream().map(s -> s.split(":"))
                    .collect(Collectors.toMap(e -> e[0], e -> e[1])).size());
        } catch (Exception e) {
            System.out.println("This \"one line\" will give nightmare to future maintainers. Is it true?");
            System.out.println("Please refer to \"https://stackoverflow.com/questions/10514473/string-to-hashmap-java\"");
        }
    }

}

出处:http://blog.csdn.net/kangkanglou/article/details/75324079

    原文作者:gaohe7091
    原文地址: https://blog.csdn.net/gaohe7091/article/details/79208659
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞