Lambda – converts the string list to a sorted map string length as the key
•
Java
I have a list < string > and I have to convert it into a map. By grouping strings of the same length into a list, I use the string length as the key to sort the order It can be used –
Map<Integer,List<String>> result = new TreeMap<>(); for (String str : list) { if (!result.containsKey(str.length())) { result.put(str.length(),new ArrayList<>()); } result.get(str.length()).add(str); }
How can we use Java 8 streaming?
Solution
You can use stream to:
Map<Integer,List<String>> result = list.stream() .collect(Collectors.groupingBy( String::length,// use length of string as key TreeMap::new,// create a TreeMap Collectors.toList())); // the values is a list of strings
This is done by accepting collectors with 3 parameters Groupingby overload to collect streams: key mapper functions, mapped providers, and downstream collectors
However, there is a more concise approach without streams:
Map<Integer,List<String>> result = new TreeMap<>(); list.forEach(s -> result.computeIfAbsent(s.length(),k -> new ArrayList<>()).add(s));
This uses list Foreach and map Computeifabsent to achieve what you want
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码