Mapper in Stream

Stream Function mapper

mapper is a stateless function which is applied to each element and the function returns the new stream.

In this example we will see how mapper can convert one Object to another Object. In simple words we can create objects using flowing data.

Here we are creating PubgPlayers object by passing names in constructor of class using map() method.

Look at the code its HALWA.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package com.tachyon.basic;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class StreamMapper {

	static class PubgPlayers{
		String country = "India";
		String name;
		public PubgPlayers(String name) {
			this.name = name;
		}
		public String getCountry() {
			return country;
		}
		public void setCountry(String country) {
			this.country = country;
		}
		public String getName() {
			return name;
		}
		public void setName(String name) {
			this.name = name;
		}
		@Override
		public String toString() {
			return "PubgPlayers [country=" + country + ", name=" + name + "]";
		}
		
		
	}
	
	public static void main(String[] args) {
		List<String> names = Arrays.asList("Shroud","Mortal","Dynamo","kronten");
			
		List<PubgPlayers> indianPlayer = names.stream()
				.filter(i -> !i.startsWith("S"))
				// make new PubgPlayers object using names
				.map(i -> {
					PubgPlayers player = new PubgPlayers(i);
					return player;
				})
				// storing as a list of players
				.collect(Collectors.toList());
		indianPlayer.forEach(System.out::println);
	}
	
}

We can make it more shorter using this

1
2
3
4
5
6
7
8
9
List<PubgPlayers> indianPlayer = names.stream()
				.filter(i -> !i.startsWith("S"))
				// make new PubgPlayers object using names
				.map(i -> {
					return new PubgPlayers(i);
				})
				// storing as a list of players
				.collect(Collectors.toList());

Even more shorten using this

1
2
3
4
5
6
7
List<PubgPlayers> indianPlayer = names.stream()
				.filter(i -> !i.startsWith("S"))
				// make new PubgPlayers object using names
				.map(PubgPlayers::new)
				// storing as a list of players
				.collect(Collectors.toList());

will add more content

Comments