Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create recursive tree-like data structure in java using Map<String, T>?

I have a mind-block when trying to create data-structure that follows the pattern:

Map<String, T> is a main building block and T is either Map<String, T> or as terminal operator List<String>. Is it possible to build anything similar in Java, this idea comes from functional languages like F# or Haskell-like.

I searched SO but so far couldn't find anything that match my idea in Java.

like image 405
Dmytro Chasovskyi Avatar asked Feb 18 '19 08:02

Dmytro Chasovskyi


2 Answers

Yes: you can do something like this:

public abstract class T {
...
}
public class NonTerminal extends T {
    private Map<String,T> map = new HashMap<>();
...
}
public class Terminal extends T {
    private List<String> list;
---
}
like image 153
Maurice Perry Avatar answered Sep 19 '22 06:09

Maurice Perry


Recreating functional programming stuff in Java isn't really a good idea (at least not in Java 8, I don't know about Java 11).

You can do something like this:

class EitherMapOrList {
    private Map<String, EitherMapOrList> map;
    private List<String> list;

    public EitherMapOrList(Map<String, EitherMapOrList> map) {
        this.map = map;
    }

    public EitherMapOrList(List<String> list) {
        this.list = list;
    }
    // you can remove the optionals here and use null directly.
    public Optional<Map<String, EitherMapOrList>> getMap() {
        return Optional.ofNullable(map);
    }

    public Optional<List<String>> getList() {
        return Optional.ofNullable(list);
    }
}

And then create a Map<String, EitherMapOrList>.

But I would imagine it would be a pain to use this thing in Java.

like image 20
Sweeper Avatar answered Sep 20 '22 06:09

Sweeper