Search code examples
javastringhashmaptreemap

How to put the string stored in the treeMap in java


I have a String a = "1x^2 2x^3 3x^4 4x^4 " and I want to store the power in each term as key and coefficient as value to treeMap. Since there is two same power with different coefficients, I need to sum up coefficients so that the result is {2=1,3=2,4=7}. Because treemap.put(key) can only override the previous value with the same key so I could only get the result as{2=1,3=2,4=4}. How to solve that?


Solution

  • It is recommended to use Map::merge function to accumulate the values for multiple identical keys:

    Map<Integer, Integer> terms = new TreeMap<>();
    for (String term : a.split("\\s+")) {
        String[] pair = term.split("x\\^");
        terms.merge(Integer.valueOf(pair[1]), Integer.valueOf(pair[0]), Integer::sum);
    }
    System.out.println(terms);
    

    Output:

    {2=1, 3=2, 4=7}
    

    Using Stream API this can be resolved using Collectors.toMap in a similar way using Integer::sum as a merge function:

    String a = "1x^2 2x^3 3x^4 4x^4 ";
    
    Map<Integer, Integer> terms = Arrays.stream(a.split("\\s+")) // Stream<String>
            .map(t -> t.split("x\\^")) // Stream<String[]>
            .collect(Collectors.toMap(
                    t -> Integer.valueOf(t[1]), // power as key
                    t -> Integer.valueOf(t[0]), // coefficient as value
                    Integer::sum,               // add coefficients for the same power
                    TreeMap::new     // supply TreeMap as result
            ));
    
    System.out.println(terms);
    

    Output:

    {2=1, 3=2, 4=7}