Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Passing a Map as a function parameter

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";
}
?>
like image 977
TeamBlast Avatar asked Dec 09 '22 07:12

TeamBlast


2 Answers

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:

  • Map in the Java 6 documentation
  • HashMap in the Java 6 documentation
like image 115
Sebastian Paaske Tørholm Avatar answered Dec 28 '22 04:12

Sebastian Paaske Tørholm


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.

like image 29
phihag Avatar answered Dec 28 '22 03:12

phihag