2

I have these two methods:

 @Override
  public void done(E e, Map.Entry<String, T> m) {

  }

  @Override
  public void done(E e, String k, T v) {
     this.done(e, null);
  }

instead of passing null, how can I create a new Map.Entry? I tried:

this.done(e, Map.of(k,v));

but that creates a Map not a Map.Entry.

Naman
  • 27,789
  • 26
  • 218
  • 353

1 Answers1

6

With Java 9+, you can use Map.entry as:

static <E, T> void done(E e, Map.Entry<String, T> m) {
     // do something
}

// using immutable entry
static <E, T> void done(E e, String k, T v) {
    done(e, Map.entry(k, v));
}

// using mutable entry 
static <E, T> void done(E e, String k, T v) {
    done(e, new AbstractMap.SimpleEntry<>(k, v));
}
hisener
  • 1,431
  • 1
  • 17
  • 23
Naman
  • 27,789
  • 26
  • 218
  • 353
  • 3
    Nice (+1). It should be noted though, that `Map.entry(k, v)` will return an immutable entry. If changes are required, I guess we still need to use the good old `AbstractMap.SimpleEntry`. – Kartik Feb 09 '19 at 03:40
  • 1
    @Kartik ofcourse, thanks updated. – Naman Feb 09 '19 at 03:46
  • @Kartik the constraints on `Map.entry` are the same as for `Map.of` (e.g. not only immutable but also disallowing `null`), which the OP seems to already know. – Holger Feb 10 '19 at 12:33