Learn how to convert String to Integer using Java 8 with Integer::valueOf method reference and functional interface example with output.
Code Explanation (Step-by-Step) :-
- Convertor is a Functional Interface that defines one method to convert a value from one type to another.
- In this program, the input type is String , and the output type is Integer.
- Integer::valueOf is used as a method reference to convert the given String into an Integer.
- The method interface is assigned to the convert() method of the Convertor interface.
- When con.convert(“123”) is called, it internally calls Integer.valueOf(“123”).
- The returned Integer value is stored in the value variable.
- Finally, the program prints the converted integer value 123.
@FunctionalInterface
interface Convertor {
T convert(F from);
}
public class TestStream {
public static void main(String[] args) {
Convertor con = Integer::valueOf;
Integer value = con.convert("123");
System.out.println(value);
}
}
Output :- 123
Difference Between Integer::valueOf and Integer.parseInt() –
- Return Type
- Integer::valueOf returns an Integer object.
- Integer.parseInt() returns a primitive int value.
- Usage
- Integer::valueOf is commonly used when an object is needed.
- Integer.parseInt() is used when a primitive integer is enough.
- Java 8 Method Reference Support
- Integer::valueOf can be used directly as a method reference in Java 8.
- Integer.parseInt() can also be used as a method reference, but it returns int instead of Integer.
- Performance
- Integer.parseInt() is slightly more efficient when you only need a primitive int.
- Integer::valueOf may involve object creation or caching, so it is useful when working with objects.
- Use Case
- Use Integer::valueOf when working with collections, generics, or functional interfaces that require Integer.
- Use Integer.parseInt() when you only need a numeric primitive value for calculations.
FAQ :
Can Integer::valueOf throw an exception?
Yes, it throws NumberFormatException if the input String contains invalid numeric data.