Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,859 questions

51,780 answers

573 users

How to create a method that takes a lambda expression as a parameter in Java

2 Answers

0 votes
interface StringFunction {
  String run(String str);
}

public class Main {
  public static void main(String[] args) {
    StringFunction num24 = (s) -> s + "24";
    StringFunction num25 = (s) -> s + "25";
    
    printFormatted("Java", num24);
    printFormatted("Java", num25);
  }
  public static void printFormatted(String str, StringFunction format) {
    String result = format.run(str);

    System.out.println(result);
  }
}


/*
run:

Java24
Java25

*/

 



answered May 3, 2025 by avibootz
0 votes
import java.util.function.Consumer;

public class Main {
    // Method that accepts a lambda expression as a parameter
    public static void processList(int[] numbers, Consumer<Integer> action) {
        for (int num : numbers) {
            action.accept(num); // Apply the lambda action to each element
        }
    }

    public static void main(String[] args) {
        int[] numbers = {1, 2, 3, 4, 5, 6};

        // Passing a lambda expression to print each number
        processList(numbers, num -> System.out.println("Number: " + num));
        
        System.out.println();

        // Passing a lambda expression to double each number and print it
        processList(numbers, num -> System.out.println("Double Number: " + (num * 2)));
    }
}


/*
run:

Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
Number: 6

Double Number: 2
Double Number: 4
Double Number: 6
Double Number: 8
Double Number: 10
Double Number: 12

*/

 



answered May 3, 2025 by avibootz
...