In this tutorial Java 8 Stream map example, we will show you few Java 8 map examples to demonstrate the use of Streams map() and can be used with mapToInt(), collect() and average(). map() returns a Stream instance processed by a given Function. Here, We need to pass Function instance as lambda expression.
Let’s dig deeper via examples:
Uppercase a list of Strings
Simple Java example to convert a list of Strings to upper case
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
public static void main(String[] args) { List<String> alpha = Arrays.asList("java", "nodejs", "php", "c#"); List<String> result = alpha.stream().map(String::toUpperCase).collect(Collectors.toList()); System.out.println(result); List<Integer> num = Arrays.asList(11, 22, 33, 44, 55); List<Integer> result1 = num.stream().map(n -> n * 2).collect(Collectors.toList()); System.out.println(result1); List<Integer> result2 = num.stream().map(n -> { if (n%2!=0) n = n*2; return n; }).collect(Collectors.toList()); System.out.println(result2); } |
Output
1 2 3 |
[JAVA, NODEJS, PHP, C#] [22, 44, 66, 88, 110] [22, 22, 66, 44, 110] |
List of objects -> List of String
Fetch all the name values from a list of the People objects.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
public static void main(String[] args) { List<People> Peoples = Arrays.asList(new People(30,"M","Mr A"), new People(24,"M","Mr B"), new People(31,"M","Mr B")); // Java 8 List<String> collect = Peoples.stream().map(x -> x.getName()).collect(Collectors.toList()); System.out.println(collect); //calculate age of average Peoples.stream().mapToInt(x -> x.getAge()).average().ifPresent(System.out::println); } |
Output
1 2 |
[Mr A, Mr B, Mr B] 28.333333333333332 |
List of objects -> List of other objects
This example shows you the way to convert a list of People objects into a list of PeopleExt objects.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
public static void main(String[] args) { List<People> peoples = Arrays.asList(new People(30,"M","Mr A"), new People(24,"M","Mr B"), new People(31,"M","Mr B")); // convert object to other object inside method map(). List<PeopleExt> result = peoples.stream().map(p -> { PeopleExt obj = new PeopleExt(p.getName()); if ("Mr A".equals(p.getName())) { obj.setRole("Admin"); } return obj; }).collect(Collectors.toList()); System.out.println(result); } |
Output
That’s all about Java 8 Stream map example.
Reference
Java 8 Stream
Processing Data with Java SE 8 Streams
Download complete source code, click link below
Java8StreamMapExample.zip (227 downloads)