Use different methods based on integer value

This is something that I can’t omit, now I have something like this:

boolean method1(int a){
//something
returns true;
}

boolean method2(int a){
//something
returns true;
}

for (int i; i<100; i++){
  switch (someInt){
  case 1: boolean x = method1(i);
  case 2: boolean x = method2(i);
  }


}

What I would like is to take the switch out of the loop, since someInt will remain unchanged for each i, so it needs to be solved only once, but I need x to be checked for each i, so I would need something like:

    switch (someInt){
          case 1: method1(); //will be used in loop below
          case 2: method2(); //will be used in loop below
          }

   for (int i; i<100; i++){
       boolean x = method the switch above picked
   }
+4
source share
3 answers

You can use Java 8 method references.

Here is an example:

public class WithMethodRefs {
    interface MyReference {
        boolean method(int a);
    }

    boolean method1(int a) {
        return true;
    }

    boolean method2(int a) {
        return false;
    }

    public void doIt(int someInt) {
        MyReference p = null;
        switch (someInt) {
        case 1:
            p = this::method1;
            break;
        case 2:
            p = this::method2;
            break;
        }

        for (int i = 0; i < 100; i++) {
            p.method(i);
        }
    }
}
+7
source

:

:

:

    interface CallIt {
        boolean callMe(int a);
    }

    class Method1 implements CallIt {
        public boolean callMe(int a) {
            return true;
        }
    }

    class Method2 implements CallIt {
        public boolean callMe(int a) {
            return true;
        }
    }

    void doIt(int someInt) {
        CallIt callIt = null;
        switch (someInt) {
        case 1:
            callIt = new Method1();
            break;
        case 2:
            callIt = new Method2();
            break;
        }

        for (int i = 0; i < 100; i++) {
            boolean x = callIt.callMe(i);
        }
    }
+5

My two cents. If we start functioning, we will do it to the end!

    IntFunction<IntFunction<Boolean>> basic = x -> i -> {
        switch (x) {
            case 1: return method1(i);
            case 2: return method2(i);
            default:
                throw new RuntimeException("No method for " + someInt);
        }
    };
    IntFunction<Boolean> f = basic.apply(someInt);
    IntStream.range(0, 100).forEach(i -> {
        boolean result = f.apply(i);
        //do something with the result
    });

Also, I do not see any break statements in your switch. Maybe this is because this is just an example, but check to see if they are here. You will get method2 () for all cases otherwise.

+4
source

Source: https://habr.com/ru/post/1627979/


All Articles