Map, unlike, other Collection types is in a Key/Value Format where the Keys are unique in a Map. Using Map.Entry, we can fetch the keySet() as well as entrySet().
Stream cannot be applied directly to a Map since Stream is done on the Collection of Objects. So it is applied to a keySet() or a entrySet() or values() that return the collection of value from a Map.
Map someMap = new HashMap<>();
Set> entries = someMap.entrySet();
Set keySet = someMap.keySet();
Collection values = someMap.values();
These each give us an entry point to process those collections by obtaining streams from them:
Stream> entriesStream = entries.stream();
Stream valuesStream = values.stream();
Stream keysStream = keySet.stream();
Here are few examples of Stream for a Map
package com.learning;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
import com.learning.model.Gender;
import com.learning.model.Person;
public class StreamMap {
public static void main(String args[]) {
Map personMap = new HashMap();
Person personOne = new Person(10, "John", Gender.MALE);
Person personTwo = new Person(11, "Andy", Gender.MALE);
Person personThree = new Person(12, "Peter", Gender.MALE);
Person personFour = new Person(13, "Sarah", Gender.FEMALE);
Person personFive = new Person(14, "Gillian", Gender.FEMALE);
personMap.put(personOne.getAge(), personOne);
personMap.put(personTwo.getAge(), personTwo);
personMap.put(personThree.getAge(), personThree);
personMap.put(personFour.getAge(), personFour);
personMap.put(personFive.getAge(), personFive);
// Find all Person Objects where Age is Even
System.out.println("Persons with Even Age - " + personMap.entrySet().stream().filter(person -> person.getKey() % 2 == 0)
.map(Map.Entry::getValue).collect(Collectors.toList()));
// Find all Person Objects where Gender is Female
System.out.println("Persons with Gender Female - " + personMap.values().stream().filter(person -> person.getGender().equals(Gender.FEMALE))
.collect(Collectors.toList()));
}
}
Output
Persons with Even Age - [10 John MALE, 12 Peter MALE, 14 Gillian FEMALE]
Persons with Gender Female - [13 Sarah FEMALE, 14 Gillian FEMALE]
No comments:
Post a Comment