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)),



>Solution :

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")
    // );


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

  public static String b(String s) {
    return s + "b";

Leave a Reply