Write a Java program using Lambda Expression to convert a list of integers to their corresponding binary strings
The java program that converts a list of integers to binary strings using a lambda expression and a custom functional interface NumberConverter. Here's an explanation of the code:
- The BinaryString class is defined, which contains the main method and another method named convertToBinary.
- Inside the main method:
- List<Integer> numbers = List.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);: This line creates an immutable list of integers named numbers using the List.of method. It contains a set of integers.
- System.out.println("Given Numbers : " + numbers);: This line prints the original list of numbers.
- List<String> binaryStrings = convertToBinary(numbers, Integer::toBinaryString);: This line calls the convertToBinary method, passing the numbers list as well as a method reference Integer::toBinaryString as the converter. The toBinaryString method is used to convert each integer to a binary string.
- System.out.println("Binary Numbers : " + binaryStrings);: This line prints the list of binary strings.
- The convertToBinary method is defined with the following functionality:
- List<String> result = new ArrayList<>();: This line creates an ArrayList to store the converted binary strings.
- The method iterates through each integer in the input list, applies the conversion using the provided converter, and adds the converted binary string to the result list.
- Finally, the result list containing the converted binary strings is returned.
- The NumberConverter functional interface is defined, which declares a single method named convert that takes an integer and returns a binary string. This interface is used to define the lambda expression or method reference for converting integers to binary strings.
Source Code
import java.util.ArrayList;
import java.util.List;
public class BinaryString
{
public static void main(String[] args)
{
List<Integer> numbers = List.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
System.out.println("Given Numbers : "+numbers);
List<String> binaryStrings = convertToBinary(numbers, Integer::toBinaryString);
System.out.println("Binary Number : "+binaryStrings);
}
public static List<String> convertToBinary(List<Integer> list, NumberConverter converter)
{
List<String> result = new ArrayList<>();
for (Integer num : list)
{
result.add(converter.convert(num));
}
return result;
}
}
interface NumberConverter
{
String convert(int num);
}
Output
Given Numbers : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Binary Number : [1, 10, 11, 100, 101, 110, 111, 1000, 1001, 1010]