Java: Passing a Map as a function parameter

21,122

Solution 1

public boolean foo(Map<K,V> map) {
    ...
}

Where K is the type of the keys, and V is the type of the values.

Note that Map is only an interface, so to create such a map, you'll need to create an instance of HashMap or similar, like so:

Map<K,V> map = new HashMap<K, V>();
foo(map);

See also:

Solution 2

public class ExampleClass {
  public boolean exampleFunction(Map<String,String> exampleParam) {
    return exampleParam.containsKey("exampleKey");
  }

  public static void main(String[] args) {
    Map<String,String> ourMap = new HashMap<String,String>();
    ourMap.put("exampleKey", "yes, it is set");
    ExampleClass ourObject = new ExampleClass();
    boolean ourResult = ourObject.exampleFunction(ourMap);
    System.out.print(ourResult ? "In Map" : "Not in Map");
  }
}

As you can see, just use a Map.

Share:
21,122
TeamBlast
Author by

TeamBlast

Professional in procrastination and decent programmer.

Updated on July 04, 2020

Comments

  • TeamBlast
    TeamBlast almost 4 years

    I'm new to Java, and need to know how to pass an associative array (Map) as a single parameter in a function.

    Here's what I'm wanting to do in Java, shown in PHP.

    <?php
    public class exampleClass {
     public function exampleFunction($exampleParam){
      if(isset($exampleParam['exampleKey'])){
       return true;
      }
      else {
       return false;
      }
     }
    }
    $ourMap = array(
     'exampleKey' => "yes, it is set"
    );
    $ourClass = new exampleClass();
    $ourResult = $ourClass->exampleFunction($ourMap);
    if(!$ourResult){
     echo "In Map";
    }
    else {
     echo "Not in Map";
    }
    ?>