D
D
devpy142021-01-09 13:29:41
Java
devpy14, 2021-01-09 13:29:41

How to convert String[] to Map via Stream API?

There is an array of strings:
String[] array = {"name", "Ivanov", "country", "Ukraine", "city", "Kiev", "age", null};

need to convert to Map trace. view using the Stream API:
{name=Ivanov, country=Ukraine, city=Kiev, age=null}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Erik Mironov, 2021-01-09
@devpy14

If you need keys and values ​​in original order, then use LinkedHashMap.

String[] array = {"name", "Ivanov", "country", "Ukraine", "city", "Kiev", "age", null};

       Map<String, String> map = Stream.iterate(
                Arrays.asList(array), list -> list.subList(2, list.size()))
                .limit(array.length / 2)
                .collect(Collectors.toMap(
                        list -> list.get(0) == null ? "null" : list.get(0),
                        list -> list.get(1) == null ? "null" : list.get(1),
                        (x, y) -> y, LinkedHashMap::new));

        map.entrySet().forEach(System.out::println);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question