Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading