Lambda expressions in java

 Lambda expressions in java


Lambda expressions are a feature in Java that allow developers to write concise, functional-style code. Here is an example of how to use lambda expressions in Java:



import java.util.Arrays;


public class Main {

  public static void main(String[] args) {

    String[] fruits = {"apple", "banana", "orange", "pear"};


    Arrays.sort(fruits, (a, b) -> a.compareTo(b));


    for (String fruit : fruits) {

      System.out.println(fruit);

    }

  }

}

In this example, we define an array of strings called fruits. We then use the Arrays.sort method to sort the array in alphabetical order. We pass a lambda expression as the second argument to the Arrays.sort method. The lambda expression takes two strings a and b and compares them using the compareTo method. Finally, we use a for loop to iterate over the sorted array and print each fruit to the console.

No comments:

Post a Comment

The Importance of Cybersecurity in the Digital Age

 The Importance of Cybersecurity in the Digital Age Introduction: In today's digital age, where technology is deeply intertwined with ev...