Switch case implementation in Java for an integer pair combination

switch case in java example programs
java 8 switch case lambda
java switch multiple case
switch statement java
switch case java 8
how to exit from switch case in java
java switch enum
empty switch case java

I have following python code -

def get_subject_from_stream_id_and_subject_id(stream_id, subject_id):
#(stream_id, subject_id): ("subject_name")
return {
    (1, 1): "Accounts",
    (1, 2): "English",
    (1, 3): "Organization of Commerce",
    (2, 1): "Physics",
    (2, 2): "English",
    (2, 3): "Biology"
}.get((stream_id, subject_id), "None")

In this code, I want to get subject name from the integer pair combination i.e. stream_id, subject_id e.g. (1, 2) is for English. It was implemented using python tuple.

I want to implement the same piece of code in Java.

Could someone write this in a better way in Java?

public String getSubjectFromStreamIdAndSubjectId(int streamId, int subjectId) {
  switch (streamId) {
    case 1:
        switch (subjectId) {
        case 1:
            return "Accounts";
        case 2:
            return "English";
        case 3:
            return "Organization of Commerce";
        default:
            return null;
        }

    case 2:
        switch (subjectId) {
        case 1:
            return "Physics";
        case 2:
            return "English";
        case 3:
            return "Biology";
        default:
            return null;
        }
    default:
        return null;
   }
}

Thank you.

I don't like the solution presented in the duplication suggestion Switching on a pair of `int`s. for two reasons:

  1. The solution relies on external logic (Integer.valueOf() and switch of String) while it is not probable, the implementations may vary in future JDK releases
  2. the switch-case was designed as shorthand for series of if statements. is not the best solution for mapping input to output values. A better solution is to utilize the Map data structure

The proper solution in my eyes would involve some kind Java Tuple. while there is no Tuple in the JDK, one can be easily constructed as user defined class. In fact, there is already an SO answer about that: A Java collection of value pairs? (tuples?) so if we use the class from the above-mentioned answer as Map key, the solution is fairly easy and much more extensible (you could, for instance, load the map from an external resource like text file or DB table):

// initialized using instance initializer
Map<Pair<Integer, Integer>, String> streamIdAndSubjectIdMap = new HashMap<>()
{
    {
        put(new Pair(1, 1), "Accounts");
        put(new Pair(1, 2), "English");
        put(new Pair(1, 3), "Organization of Commerce");
    }
};

public String getSubjectFromStreamIdAndSubjectId(int streamId, int subjectId) {
    return streamIdAndSubjectIdMap.get(new Pair<>(streamId, subjectId));
}

Flow control in Java, Java equivalent of the above Python code goes more like this: private static final Map<List<Integer>, String> SUBJECT_MAP� Few points about Switch Case. 1) Case doesn’t always need to have order 1, 2, 3 and so on. It can have any integer value after case keyword. Also, case doesn’t need to be in an ascending order always, you can specify them in any order based on the requirement. 2) You can also use characters in switch case. for example –

Personally, i would really recommend to not use the switch statement here, since any hacks (like String concatenation) will just complicate things. However, you could refactor this method to use a regular if expression with a return statement.

public static String getSubject(int streamId, int subjectId) {
    Pair<Integer> pair = Pair.of(streamId, subjectId);

    if (pair.equals(Pair.of(1, 1))) {
        return "Subject";
    }
    if (pair.equals(Pair.of(1, 2))) {
        return "English";
    }
    if (pair.equals(Pair.of(1, 3))) {
        return "Organization of Commerce";
    }
    if (pair.equals(Pair.of(2, 1))) {
        return "Physics";
    }
    if (pair.equals(Pair.of(2, 2))) {
        return "English";
    }
    if (pair.equals(Pair.of(2, 3))) {
        return "Biology";
    }

    return null;
}

At least to my eye, this looks very clean and there is no need to use an if-else expression. One thing to note here is that the Pair class needs to be implemented correctly regarding equals and hashCode for this to work. An example implementation might be the following (tough it can still be extended):

public class Pair<T> {

    private T first;
    private T second;

    public static <T> Pair<T> of(T first, T second) {
        return new Pair<>(first, second);
    }

    private Pair(T first, T second) {
        this.first = first;
        this.second = second;
    }

    public T getFirst() {
        return first;
    }

    public T getSecond() {
        return second;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Pair<?> pair = (Pair<?>) o;
        return Objects.equals(first, pair.first) &&
                Objects.equals(second, pair.second);
    }

    @Override
    public int hashCode() {
        return Objects.hash(first, second);
    }
}

The switch Statement (The Java™ Tutorials > Learning the Java , In this part of the Java tutorial, we will talk about program flow control. We will use The if keyword is followed by a pair of round brackets. Using the Scanner class of the java.util package, we read an integer value from the standard input. The previous switch statement example is rewritten using switch expression. The following rules apply to a switch statement − The variable used in a switch statement can only be integers, convertable integers (byte, short, char), strings and enums. You can have any number of case statements within a switch. Each case is followed by the value to be compared to and a colon.

It is not always recomended but in your case i would go with a nested ternary operator. If you have more combinations than given in your example this aproach could end in confusing, unreadable code. But if you have only those well defined cases:

public static String getSubjectFromStreamIdAndSubjectId(int stream_id, int subject_id) {
    return stream_id == 1 ?
            subject_id == 1 ? "Accounts" : 
            subject_id == 2 ? "English" : 
            subject_id == 3 ? "Organization of Commerce" : "None":
           stream_id == 2 ?
            subject_id == 1 ? "Physics" : 
            subject_id == 2 ? "English" : 
            subject_id == 3 ? "Biology" : "None":
           "None";
}

JDK 12: Switch Statements/Expressions in Action, The following code example, SwitchDemo , declares an int named month whose value represents a month. The code displays the name of the month, based on� Some context: I'm parsing an accounting ledger which has account1 and account2 as int types. Each is a number in the range [0, 99999]. I have many combinations to consider. Ideally I'd like to use

Java Pair Class - Learn to Implement them in Java, I used a 2x2 grid in the blog post "Enhancing Java switch Statement with Introduction of An example of this traditional switch statement that compiles and executes successfully with switch (integer). {. case 1 : numericString = "one ";. break;. case 2 : However, there are a couple of significant differences. Deciding whether to use if-then-else statements or a switch statement is based on readability and the expression that the statement is testing. An if-then-else statement can test expressions based on ranges of values or conditions, whereas a switch statement tests expressions based only on a single integer, enumerated value, or String object.

Java Basics Exercises - Java Programming Tutorial, Also, explore how to implement pair class in Java. Pair<Integer, String> pair = new Pair<>(3, "Three");; Integer key = pair. This pair or combination may result in (number, cube root of a number). Java For Loop � Java Switch Statement � Java Type Conversion � Java Null � Java Jar File � Java Exception� We were looking for an equivalent class for pair in Java but Pair class did not come into existence till Java 7. JavaFX 2.2 has the javafx.util.Pair class which can be used to store a pair. We need to store the values into Pair using the parameterized constructor provided by the javafx.util.Pair class.

Java Basics - Java Programming Tutorial, Use (a) a "nested- if " statement; (b) a " switch-case-default " statement. For example, if the int is 15423, the output shall be "3 2 4 5 1", with a space separating The program shall prompt user for a plaintext string consisting of mix-case (i = 1; i < n; ++i) { // Swap if this pair is out of order if array[i-1] > array[i] { swap( A[i-1],� Simply put, a combination is a subset of elements from a given set. Unlike permutations, the order in which we choose the individual elements doesn't matter. Instead, we only care whether a particular element is in the selection.

Comments
  • You should post this here: codereview.stackexchange.com
  • one other way is to use two arrays. If streamId == 1, use the first, if streamId == 2, get data from the second, and have subjectId match the index
  • This link has the solution for your question stackoverflow.com/questions/41831061/…
  • Possible duplicate of Switching on a pair of `int`s
  • @gcdinesh could you comment which one could be the better implementation?