String to HashMap JAVA

后端 未结 10 1309
我寻月下人不归
我寻月下人不归 2020-12-02 11:32

I have a Java Property file and there is a KEY as ORDER. So I retrieve the VALUE of that KEY using the getProperty(

10条回答
  •  独厮守ぢ
    2020-12-02 12:07

    In one line :

    HashMap map = (HashMap) Arrays.asList(str.split(",")).stream().map(s -> s.split(":")).collect(Collectors.toMap(e -> e[0], e -> Integer.parseInt(e[1])));
    

    Details:

    1) Split entry pairs and convert string array to List in order to use java.lang.Collection.Stream API from Java 1.8

    Arrays.asList(str.split(","))
    

    2) Map the resulting string list "key:value" to a string array with [0] as key and [1] as value

    map(s -> s.split(":"))
    

    3) Use collect terminal method from stream API to mutate

    collect(Collector> collector)
    

    4) Use the Collectors.toMap() static method which take two Function to perform mutation from input type to key and value type.

    toMap(Function keyMapper, Function valueMapper)
    

    where T is the input type, K the key type and U the value type.

    5) Following lambda mutate String to String key and String to Integer value

    toMap(e -> e[0], e -> Integer.parseInt(e[1]))
    



    Enjoy the stream and lambda style with Java 8. No more loops !

提交回复
热议问题