import java.util.Arrays;
import java.util.stream.Collectors;
public class StringToMap {
public static void main(String[] args) {
try {
String str = "SALES:0,SALE_PRODUCTS:1,EXPENSES:2,EXPENSES_ITEMS:3";
Arrays.asList(str.split(",")).stream().map(s -> s.split(":"))
.collect(Collectors.toMap(e -> e[0], e -> e[1])).forEach((key, value) -> {
System.out.println("key = " + key + ",value = " + value);
});
System.out.println();
Arrays.asList(str.split(",")).stream().map(s -> s.split(":"))
.collect(Collectors.toMap(e -> e[0], e -> Integer.parseInt(e[1]))).forEach((key, value) -> {
System.out.println("key = " + key + ",value + 10 = " + (value + 10));
});
System.out.println();
System.out.println(Arrays.asList(str.split(",")).stream().map(s -> s.split(":"))
.collect(Collectors.toMap(e -> e[0], e -> e[1])).size());
} catch (Exception e) {
System.out.println("This \"one line\" will give nightmare to future maintainers. Is it true?");
System.out.println("Please refer to \"https://stackoverflow.com/questions/10514473/string-to-hashmap-java\"");
}
}
}
出处:http://blog.csdn.net/kangkanglou/article/details/75324079