0

I changes the question so it will be more clear, please see the example below.

Can I create a dictionary in Java any sort of map list, where the value is a function?

if yes, how do I do it and how can I iterate it to call the functions ?

I want something like this:

       dictionary values
       { 
           0: { name1, func1)
           1: {name2, func2)
           .....
           .....
       }



      for (values value: values.getValues())
      {
               ///does something with
                dictionary[value][0] //doing soething with the name
                dictionary[value][1]() //calling the function
       }
Ohad
  • 1,563
  • 2
  • 20
  • 44
  • What do you mean? In a map, you can speak of a key and a value. But in a list of enums, there is no "value" . It's probably best to post the code that you have and show where you are stuck. – Erwin Bolwidt Nov 19 '17 at 12:17
  • This is unclear. Are you saying that you want your enum instances to have a member variable of type `List`? Can you add some pseudocode to illustrate what you'd like to be able to do? – Oliver Charlesworth Nov 19 '17 at 12:17
  • yes I can add... – Ohad Nov 19 '17 at 12:17
  • The answer is a vague »yes, sort of«, but it depends on what you want to do, specifically. The enum values itself cannot be methods, but you can have a method on the enum that does something based on which enum value it is. Or, if the function only returns constant values of some sort, you add those to the constructor of the enum and add a getter to the enum class. – Ingo Bürk Nov 19 '17 at 12:21
  • `enum Foo { VALUE_A(5), VALUE_B(10); private final int value; Foo(int value) { this.value = value; } public int getValue() { return value; } }` is an example for the second option. – Ingo Bürk Nov 19 '17 at 12:22
  • Instead of `int` you can also use the type `Runnable` or `Supplier` etc. to implement a function directly – though the usefulness of that is quite limited. – Ingo Bürk Nov 19 '17 at 12:23
  • 2
    You enum has not enum constants. I'm not sure what you mean with `field1(func1)` exactly. Why do think you need to use an enum and not just a list of functions (this is what your for-loop suggests)? It still doesn't make much sense. – Erwin Bolwidt Nov 19 '17 at 12:33
  • this is exactly what I need. I can do it in python easily. – Ohad Nov 19 '17 at 12:52
  • Relevant? https://stackoverflow.com/questions/17610041/maps-in-java-maps-can-i-assign-a-function-to-the-value-in-the-k-v-pair (and a lot of similar ones) This seems to me a duplicate, "how do I store a function in structure XYZ in Java" has come up before. – Mörre Nov 19 '17 at 13:16

0 Answers0