Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is it possible to pass an argument into a map in Java?

I would like to pass a value someValue, into this Map. And was wondering if there was a way to do this.
The idea is to call the getData.get("code")(someValue) It would call a function and pass in the correct value.

private static final Map<String, String> getData = Map.ofEntries(
  Map.entry("code", someSearch.getCode(someValue)),

  Map.entry("foo", someSearch.bar(anotherValue)
);


getData.get("code");

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You can use the Function type to use a function as a variable and then store instances of functions within the map that you can retrieve and call dynamically. For example:

import java.util.*;
import java.util.function.Function;

class Main {  
  public static void main(String args[]) { 
    // Using method references
    Map<String, Function<String, String>> map = Map.ofEntries(
      Map.entry("a", Main::a),
      Map.entry("b", Main::b)
    );

    // Alternatively, using lambdas
    // Map<String, Function<String, String>> map = Map.ofEntries(
    //   Map.entry("a", (s) -> s + "a"),
    //   Map.entry("b", (s) -> s + "b")
    // );

    System.out.println(map.get("a").apply("test"));
  }

  public static String a(String s) {
    return s + "a";
  }

  public static String b(String s) {
    return s + "b";
  }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading