Java List<String> to Map<String, String> using Stream
To convert a list of strings to a map of string-string in Java, you can use the 'stream' and 'collect' methods from the 'Stream' class. Here's an example:
List<String> data = Org.getResult().getData();
Map<String, String> map = data.stream()
.collect(Collectors.toMap(Function.identity(), Function.identity()));
// Print the resulting map
map.forEach((key, value) -> System.out.println(key + ' : ' + value));
In this example, 'data.stream()' converts the list into a stream, and then we use 'collect' to collect the elements of the stream into a map. The 'Function.identity()' method is used as both the key and value mapper, which means each string in the list will be used as both the key and the value in the resulting map.
Note that if there are duplicate keys in the list, a 'java.lang.IllegalStateException' will be thrown. If you want to handle duplicate keys, you can provide a merge function as the fourth argument to the 'toMap' method.
Also, make sure to import the necessary classes:
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
原文地址: https://www.cveoy.top/t/topic/o1UI 著作权归作者所有。请勿转载和采集!