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.
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;
---
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With