Java 8 Stream map() examples
In this article, we are going to check some Java 8 Stream map() examples. We create a map of the user and try to do some basic operations using the Java 8 Stream map() api. Java 8 stream Api has a lot of other Api’s as well which is of great use.
Create a User Bean:-
We are creating a bean with some basic getters and setter.
public class User {
int id;
String name;
public User(int id, String name) {
super();
this.id = id;
this.name = name;
}
//
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + "]";
}
}
How to Create a Map Of users Using Java 8 stream map()
Map<Integer, User> userMap = new HashMap<>();
userMap.put(1, new User(1, "Google"));
userMap.put(2, new User(2, "Frugalis"));
userMap.put(3, new User(3, "Minds"));
How to Iterate Map and Show Values using map()
userMap.forEach((K,V)->System.out.println(V.toString()));
List<Integer> output_3 = userMap.keySet().stream()
.collect(Collectors.toList());
List<User> output_4 = userMap.values().stream()
.collect(Collectors.toList());
OutPut:-
User [id=1, name=Google]
User [id=2, name=Frugalis]
User [id=3, name=Minds]
In Java 8 collections we can use expressions inside parenthesis bracket and pass parameters.
In the second list of our Java 8 Stream map() example, we are iterating using Keys of the map and iterating values and store map into a list.
How to Convert Map to List Java 8
output_3.forEach(System.out::println);
List<User> output_5 = userMap.values().stream()
.filter((x) -> x.id>1)
.collect(Collectors.toList());
output_5.forEach((x)->{
System.out.println(x.name);
});
OutPut:-
2
3
Frugalis
Minds
We are using a filter to filter the map and put values in the List.
As you notice we have filtered the list map element with an id greater than 1 from our Hashmap.
We are getting an output as 2,3 because we have printed list of keys.
How to Convert List To a Map:-
We are going to create a list of Users and will try and convert the list to a map.
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class MapTestCode{
public static <E> void main(String[] args) {
List<User> Alluser=new ArrayList<User>();
Alluser.add(new User(1, "Frugalis"));
Alluser.add(new User(2, "Sanjay"));
Alluser.add(new User(3, "John"));
Alluser.add(new User(4, "Sasha"));
Map<Integer, String> userresult1 = Alluser.stream().collect(
Collectors.toMap(x -> x.getId(), x -> x.getName()));
Map<Integer, String> userResult2 = Alluser.stream().collect(
Collectors.toMap(User::getId, User::getName));
System.out.println(userresult1);
System.out.println(userResult2);
}
}
Output:-
{1=Frugalis, 2=Sanjay, 3=John, 4=Sasha}
{1=Frugalis, 2=Sanjay, 3=John, 4=Sasha}
How to Modify A Map using Java 8
There are various methods present in java to modify a map using put, contains and other methods.
Let’s say we are having following map and we want to modify the map only if any key is found or already present . let’s see how we will do in prior to Java 8.
How to Update Map if key is Present
Let’s first look at the old way using put
and containsKey
with the following map.
Map<String, List<String>> listmap = new HashMap<String, List<String>>();
if (listmap.containsKey("India")) {
listmap.put("India", new ArrayList<String>()).add("Hyd");
}
Let’s see how we are going to do using Java 8 stream map
listmap.computeIfPresent("India",
(key, value) -> new ArrayList<String>()).add("Hyd");
How to Update A Map if No Key Is Present
Let’s first look at the old way using put
and containsKey
with the following map.
Map<String, List<String>> listmap = new HashMap<String, List<String>>();
if (!listmap.containsKey("India")) {
listmap.put("India", new ArrayList<String>()).add("Hyd");
}
Let’s see how we are going to do using Java 8 stream map.
listmap.puteIfAbsent("India",
(key, value) -> new ArrayList<String>()).add("Hyd");
Both the ways that we have demonstrated are most commonly used stream api methods and operations in a typical Java code base.We see how this declarative way makes our code concise and readable.
If we use puteIfAbsent a value null will be returned if the key-value mapping is successfully added to the hashmap object while if the id is already present on the hashmap the value which is already existing will return instead.
Go ahead and find out how can you replace your current code and use some Java 8 Stram map().
Since putIfAbsent
takes a value and put in the map directly, it doesn’t provide any laziness. If you want a bit more laziness better use computeIfAbsent.
Please Feel free to Put Your comments and let me know What do you think about this Post and What posts do you Want? Contact me anytime Here.
How to Filter null values from a Stream
If you do not filter null values , then it will print the existing values as it is . We need a custom , lets see how we can filter the null values.
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class NullExample {
public static void main(String[] args) {
List<String> listoftest = Arrays.asList("test1", "test2", null, "test3", null);
List<String> resultOp = listoftest.stream()
.filter(str -> str!=null)
.collect(Collectors.toList());
resultOp.forEach(System.out::println);
}
}
Output:
test1 test2 test3