Java 8 Streams filter examples

Category : Java | Sub Category : Java 8 Features | By Prasad Bonam Last updated: 2020-09-30 08:56:11 Viewed : 664


1. Java 8 Streams filter examples:

·       Streams let you process data in a declarative way. We do not say how to process the data, we

       just say what to do with the data.

·       Let’s say we need to find all transactions of type ‘grocery’ and return a list of transaction

·       IDs sorted in decreasing order of transaction value.

·       Stream as an abstraction for expressing efficient, SQL-like operations on a collection of data.


2. Before Java 8:

  find all transactions of type is grocery, then return the set of transaction IDs sorted in descending order of transaction value.  

           List<Transaction> groceryTransactions = new ArrayList<>();

           for(Transaction t: groceryTransactions){

            if(t.getType() == Transaction.GROCERY){

            groceryTransactions.add(t);

            }

           }

           Collections.sort(groceryTransactions, new Comparator(){

                @Override

            public int compare(Transaction t1, Transaction t2){

            return t2.getValue().compareTo(t1.getValue());

            }

           });

           List<Integer> transactionsIds = new ArrayList<>();

           for(Transaction t: groceryTransactions){

            transactionsIds.add(t.getId());

         }


3. By using Java 8 :


/* find all transactions of type is grocery, then return the set of transaction IDs sorted in descending order of transaction value.*/ 

List<Transaction> groceryTransactions = new ArrayList<>();

List<Transaction> transactionIds= groceryTransactions.parallelStream()

               .filter(t->t.getType()==Transaction.GROCERY)

               .sorted(comparing(Transaction::getValue).reversed)

               .map(Transaction::getId)

               .collect(toList());

4. java.util.stream.Stream: feel the power:


5. Example:

Following example illustrates about Java -filterMap 
Save the file as 
−  FilterMapExample.java
package java8features;

import java.util.HashMap;

import java.util.Map;

import java.util.function.Predicate;

import java.util.stream.Collectors;

 

public class FilterMapExample {

     public static void main(String[] args) {

           Map<Integer, String> animalMap = new HashMap<>();

           animalMap.put(1, "Ant");

           animalMap.put(2, "Bat");

           animalMap.put(3, "Cat");

           // Map -> Stream -> String

String resultStr = animalMap.entrySet().stream()

.map(x -> x.getValue()).collect(Collectors.joining(","));

     System.out.println("resultStr " + resultStr);


            // Map -> Stream -> Filter -> MAP

      Map<Integer, String> collectMap = animalMap.entrySet()

   .stream().filter(map -> map.getKey() <= 3) 

       .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

           System.out.println("collectMap " + collectMap);

 

           // Java 8 Predicate example 

 Map<Integer, String> predicateMap =

   filterByValue(animalMapx ->(x.contains("Cat") && !x.contains("Bat")));

               System.out.println(predicateMap);

     }

 

     // Generic Map filterbyvalue, with predicate

     public static <K, V> Map<K, V> filterByValue(Map<K, V> map, Predicate<V> predicate) {

  return map.entrySet().stream().filter(x -> predicate.test(x.getValue()))

         .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

        }

}

OutPut:

resultStr Ant,Bat,Cat

collectMap {1=Ant, 2=Bat, 3=Cat}

{3=Cat}

Search
Related Articles

Leave a Comment: