Sitemap
Aldyputu

Aldyputu

Java: Switch Lambda

1 min readNov 29, 2023

Java version 14, the switch updated with lambda. It can stop the usage of break. In java, lambda written with “->” and it it will stop the line code when condition meet and execute the lambda. Let’s see the code below:

public class LambdaTrain {
public static void main(String[] args) {
var nilai = "A";

switch (nilai){
case "A" -> System.out.println("Anda lulus dengan baik");
case "B", "C" -> System.out.println("Anda lulus"); //case with multiple condition
case "D" -> System.out.println("Anda tidak lulus");
default {
System.out.println("Anda sepertinya salah jurusan");
}
};
}
}

Another keyword that exist in java 14++ is Yield.

Get Aldyputu’s stories in your inbox

Join Medium for free to get updates from this writer.

Yield; as you can see above code, we repeatedly using println to print the information that meet the condition. Instead of putting all println statement, we can define the string variable, and yield the string per condition. Always remember, the yield is wombo combo for switch statement(I think). Let’s try to write it:

public class LambdaTrain {
public static void main(String[] args) {
var nilai = "A";

//define the variable and string type for the output
String ucapan = switch (nilai){
case "A":
yield "Anda lulus dengan baik";
case "B", "C":
yield "Anda lulus";
case "D"
yield "Anda tidak lulus";
default:
yield "Anda sepertinya salah jurusan";
}; //dont forget to close the switch block with semicolon

System.out.println(ucapan);
}
}

--

--