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";
}
?>
                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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With