I have a List of data of type String, trying to get the count of each string as Map<String, Long>
List<String> dataList = new ArrayList();
dataList.addAll(Arrays.asList(new String[] {"a", "z", "c", "b", "a"}));
System.out.println(dataList.stream().collect(Collectors.groupingBy(w -> w, Collectors.counting())));
Output is {a=2, b=2, c=1, z=1}
. I wanted the output to maintain the order as provided in list. Like, {a=2, z=1, c=1, b=2}
.
LinkedHashMap
will maintain the order, but not sure how to user Collectors.groupingBy()
to cast output to LinkedHashMap
.
Trying to solve the problem using Java8-stream