JAVA 8- Difference between boxed and map.
In Java 8, the boxed
method and the map
method serve different purposes in the context of the Stream API:
boxed
method:
- The
boxed
method is used to convert a stream of primitive values (likeIntStream
,DoubleStream
,LongStream
) into a stream of their corresponding wrapper classes (e.g.,Integer
,Double
,Long
). - It’s often used when you have a stream of primitive values, and you want to work with them as objects in situations where object-oriented features are needed.
import java.util.stream.IntStream;
import java.util.List;
import java.util.stream.Collectors;
public class BoxedExample {
public static void main(String[] args) {
int[] intArray = {1, 2, 3, 4, 5};
// Using boxed to convert IntStream to Stream<Integer>
List<Integer> integerList = IntStream.of(intArray)
.boxed()
.collect(Collectors.toList());
// Print the list of boxed integers
System.out.println(integerList);
}
}
2. map
method:
- The
map
method is used for transforming the elements of a stream by applying a function to each element. - It is not specific to primitive types and can be used with any type of stream, including streams of objects.
- It transforms each element of the stream based on the provided function.
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class MapExample {
public static void main(String[] args) {
List<String> words = Arrays.asList("apple", "banana", "orange");
// Using map to transform each element to uppercase
List<String> uppercasedWords = words.stream()
.map(String::toUpperCase)
.collect(Collectors.toList());
// Print the transformed elements
System.out.println(uppercasedWords);
}
}
Difference:
boxed()
is specifically for converting a primitive stream to a stream of boxed objects.map()
is a more general-purpose operation for transforming elements of a stream, and it can be used for both primitive and object streams.
In some cases, you might see the mapToObj
method used instead of boxed()
when converting a primitive stream to an object stream. For example:
int[] primitiveIntArray = {1, 2, 3, 4, 5};
// Using mapToObj() to convert int stream to Integer stream
List<Integer> integerList = Arrays.stream(primitiveIntArray)
.mapToObj(Integer::valueOf)
.collect(Collectors.toList());
Both boxed()
and mapToObj()
serve similar purposes in terms of converting primitive streams to object streams.
In summary,
boxed
is specifically for converting primitive streams to streams of boxed values, while map
is a general-purpose method for transforming elements in a stream using a provided function. The choice between them depends on your specific use case and the types of streams you are working with.