String to HashMap JAVA

后端 未结 10 1238
我寻月下人不归
我寻月下人不归 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<String, Integer> map = (HashMap<String, Integer>) 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<String> 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<? super String, Object, Map<Object, Object>> 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<? super T,? extends K> keyMapper, Function<? super T,? extends U> 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 !

    0 讨论(0)
  • 2020-12-02 12:12

    try

     String s = "SALES:0,SALE_PRODUCTS:1,EXPENSES:2,EXPENSES_ITEMS:3";
        HashMap<String,Integer> hm =new HashMap<String,Integer>();
        for(String s1:s.split(",")){
           String[] s2 = s1.split(":");
            hm.put(s2[0], Integer.parseInt(s2[1]));
        }
    
    0 讨论(0)
  • 2020-12-02 12:17

    I recommend using com.fasterxml.jackson.databind.ObjectMapper (Maven repo link: https://mvnrepository.com/artifact/com.fasterxml.jackson.core) like

    final ObjectMapper mapper = new ObjectMapper();
    Map<String, Object> mapFromString = new HashMap<>();
    try {
        mapFromString = mapper.readValue(theStringToParse, new TypeReference<Map<String, Object>>() {
            });
    } catch (IOException e) {
        LOG.error("Exception launched while trying to parse String to Map.", e);
    }
    
    0 讨论(0)
  • 2020-12-02 12:17

    In one line (updated)

    String s = prop.getProperty("ORDER");
    
    Map<String, Integer> orderMap = Arrays.stream(s.split(",")).map(s -> s.split(":")).collect(Collectors.toMap(s -> s[0], s -> Integer.parseInt(s[1])));
    
    0 讨论(0)
提交回复
热议问题