Filter using List
package com.demo.java8; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class Demo { public static void main(String[] args) { List<Emp> empList = Arrays.asList(new Emp[] { new Emp("1","Mumbai","20"), new Emp("2","Delhi","23"), new Emp("3","Kolkata","25"), new Emp("4","Chennai","18"), new Emp("5","Mumbai","11"), new Emp("6","Kolkata","30"), new Emp("7","Chennai","35"), new Emp("8","Mumbai","15"), new Emp("9","Delhi","22"), new Emp("10","Kolkata","27") }); //Example 1 //Filter people of City Mumbai List<Emp> filteredList1 = empList.stream() .filter(x->x.getCity().equalsIgnoreCase("mumbai")) .collect(Collectors.toList()); //Example 2 //Filter people of City Delhi who has age greater than 18 List<Emp> filteredList2 = empList.stream() .filter(x->x.getCity().equalsIgnoreCase("delhi")) .filter(x->Integer.parseInt(x.getAge())>18) .collect(Collectors.toList()); //Example 3 //Filter people of Delhi and kolkata who has if greater than 5 empList.stream() .filter(x->(x.getCity().equalsIgnoreCase("delhi") || x.getCity().equalsIgnoreCase("kolkata"))) .filter(x->Integer.parseInt(x.getId()) > 5) .forEach(System.out::println); System.out.println(filteredList1); System.out.println(filteredList2); } } class Emp{ private String id; private String city; private String age; public Emp(String id, String city, String age) { super(); this.id = id; this.city = city; this.age = age; } public String getId() {return id;} public String getCity() {return city;} public String getAge() {return age;} @Override public String toString() { return "Emp [id=" + id + ", city=" + city + ", age=" + age + "]"; } }
Filter using map
Example :
package com.demo.java8; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; public class Demo2 { public static void main(String[] args) { Map<Integer,String> monthMap = new HashMap<>(); monthMap.put(1,"JAN"); monthMap.put(2,"FEB"); monthMap.put(3,"MAR"); monthMap.put(4,"APR"); monthMap.put(5,"MAY"); monthMap.put(6,"JUN"); monthMap.put(7,"JUL"); monthMap.put(8,"AUG"); monthMap.put(9,"SEP"); monthMap.put(10,"OCT"); monthMap.put(11,"NOV"); monthMap.put(12,"DEC"); Map<Integer,String> filterMap = monthMap .entrySet() .stream() .filter(x->x.getKey() >5) // .collect(Collectors.toMap(x->x.getKey(), x->x.getValue())); //valid way but not recommended .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); //Recommended way List<String> months = monthMap.entrySet().stream() .map(x->x.getValue()) .collect(Collectors.toList()); } }