Answer the question
In order to leave comments, you need to log in
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
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 questionAsk a Question
731 491 924 answers to any question