Search code examples
javalisthashmapjava-stream

List manipulation and conversion in Java


I have an input list like:
var list = Arrays.asList("etc->hosts", "etc->dockers->ssl->certs", "root");

And I am trying to convert it into nested map:
{etc={dockers={ssl={certs={}}}, hosts={}}, root={}}

I tried to split the key from input list with dot i.e. '->' and tried to iterate over to construct a map: Map<String, Map>.
Tried.groupingBy() .computeIfAbsent() .stream().map().filter().collect(), both of them failed.


Solution

  • You don't need streams, just a simple for loop that walks down each chain:

    Map<String, Object> map = new HashMap<>();
    for (String chain : list) {
        Map<String, Object> current = map;
        for (String node : chain.split("->")) {
            current = (Map<String, Object>)current.computeIfAbsent(node, n -> new HashMap<>());
        }
    }
    

    If you want to avoid the unchecked cast warnings, you can define a self-referential map like this (assuming you don't plan to mix in additional value types):

    class NestingMap extends HashMap<String, NestingMap> {}
    

    Ideone Demo