How to Parse Strings from an ArrayList<>() into a Map<String, String>

I have a method that takes a parameter of filters that is an ArrayList<>() of strings that I need to split on ":" and put in a map.

List<String> filtersQuery = new ArrayList<>();
        filtersQuery.add("brand:nike,adidas");
        filtersQuery.add("catagory:running");

And would like the output of the map to be:

brand=nike,adidas
catagory=running

I am currently trying to use stream(). Im new to Java and running into issues with getting it to parse correctly.

>Solution :

List<String> filtersQuery = new ArrayList<>();
        filtersQuery.add("brand:nike,adidas");
        filtersQuery.add("category:running");

Map<String, String> filtersMap = filtersQuery
                .stream()
                .map(k -> k.split(":"))
                .collect(Collectors.toMap(a -> a[0],
                        a -> a[1]));

This give you better performance than @cheng gen answer

Leave a Reply