Friday, November 8, 2019

3 Examples Of Flow + Collect() Method Of Inwards Coffee 8

Hello guys, yous may know that Java 8 brought Stream API which supports a lot of functional programming operations like filtermapflatMap, reduce, together with collect. In this article, yous volition acquire most the collect() method. The collect() method of Stream shape tin last used to accumulate elements of whatever Stream into a Collection. In Java 8, yous volition oft write code which converts a Collection similar a List or Set to Stream together with so applies or so logic using functional programming methods similar the filter, map, flatMap together with so converts the effect dorsum to the Collection similar a ListSetMap, or ConcurrentMap in Java. In this terminal part, the collect() method of Stream helps. It allows yous to accumulate the effect into choice fo container yous desire similar a list, set, or a map.

Programmers oft confuse that collect() method belongs to Collector shape but that's non true. It is defined inward Stream shape together with that's why yous tin telephone telephone it on Stream later on doing whatever filtering or mapping. It accepts a Collector to accumulate elements of Stream into specified Collection.

The Collector shape provides dissimilar methods e.g. toList(), toSet(), toMap(), together with toConcurrentMap() to collect the effect of Stream into List, Set, Map, together with ConcurrentMap inward Java.

It likewise provides a special toCollection() method which tin last used to collect Stream elements into a specified Collection similar ArrayList, Vector, LinkedList or HashSet.

It's likewise a terminal functioning which agency later on calling this method on Stream, yous cannot telephone telephone whatever other method on Stream.

Btw, if yous are novel to Java or Java 8 globe so I propose yous to commencement bring together a comprehensive course of didactics similar The Complete Java MasterClass instead of learning inward bits together with pieces. The course of didactics provides a to a greater extent than structured learning textile which volition learn yous all Java fundamentals inward quick time. Once yous empathize them yous tin explore the topic yous similar yesteryear next weblog posts together with articles.




Java 8 Stream.collect() Examples

In this article, we'll come across a yoke of examples of Stream's collect() method to collect the effect of flow processing into a List, Set, together with Map inward Java. In other words, yous tin likewise say we'll convert a given Stream into List, Set, together with Map inward Java

1. Stream to List using collect()

You tin collect the effect of a Stream processing pipeline inward a listing yesteryear using the Collectors.toList() method. Just overstep the Collectors.toList() to collect() method every bit shown below:

List<String> listOfStringStartsWithJ
 = listOfString
     .stream()
     .filter( sec -> s.startsWith("J"))
     .collect(Collectors.toList());


The listing returned yesteryear the collect method volition conduct keep all the String which starts amongst "J" inward the same lodge they look inward the original listing because both Stream together with List snuff it on elements inward order. This is an of import especial which yous should know because yous oft take to procedure together with collect elements inward order.

If yous desire to acquire to a greater extent than most ordered together with unordered collection I propose yous bring together Set doesn't provider ordering together with doesn't allow duplicate, whatever duplicate from Stream volition last discarded together with lodge of elements volition last lost.

Here is an illustration to convert Stream to Set using collect() together with Collectors inward Java 8:

 brought Stream API which supports a lot of functional programming operations similar iii Examples of Stream + Collect() method of inward Java 8


The fix of String inward this illustration contains all the String which starts amongst alphabetic quality C like C and C++. The lodge volition last lost together with whatever duplicate volition last removed.



3. Stream to Map using toMap()

You tin exercise a Map from elements of Stream using collect() together with Collectors.toMap() method. Since a Map similar HashMap store 2 objects i.e. key together with value together with Stream contains simply 1 element, yous take to supply the logic to extract key together with value object from Stream element.

For example, if yous conduct keep a Stream of String so yous tin exercise a Map where the key is String itself together with value is their length, every bit shown inward the next example:

Map<String, Integer> stringToLength 
   = listOfString
        .stream()
        .collect(
            Collectors.toMap(Function.identity(), String::length));

The Function.identity() used hither denotes that same object is used every bit a key. Though yous take to last a picayune fleck careful since Map doesn't allow duplicate keys if your Stream contains duplicate elements than this conversion volition fail.

In that case, yous take to job or so other overloaded toMap() method likewise accepts an declaration to resolve conflict inward instance of duplicate keys.  Also, toMap() doesn't supply whatever guarantee on what sort of Map is returned. This is or so other of import especial yous should remember.

If yous desire to acquire to a greater extent than most dealing amongst Collections together with Stream I propose yous convey a hold back at or so other Pluralsight gem, ArrayList, HashSet, or LinkedList

There is likewise a toCollection() method inward the Collectors shape which allows yous to convert Stream to whatever collection. In the next example, nosotros volition acquire how to collect Stream elements into an ArrayList.

ArrayList<String> stringWithLengthGreaterThanTwo 
  = listOfString
      .stream()
      .filter( sec -> s.length() > 2)
      .collect(Collectors.toCollection(ArrayList::new));

Since ArrayList is a list, it provides ordering guarantee, thus all the elements inward the ArrayList volition last inward the same lodge they look inward original List together with Stream.

If yous abide by Javadoc tedious so yous tin likewise join The Complete Java MasterClass, 1 of the most comprehensive Java course of didactics on Udemy.


 brought Stream API which supports a lot of functional programming operations similar iii Examples of Stream + Collect() method of inward Java 8




Java Program to Use Stream.collect() method

Here is our consummate Java plan to demonstrate the job of collect() method of Stream shape to convert Stream into dissimilar Collection classes inward Java e.g. List, Set, Map, together with Collection itself.

import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Set; import java.util.function.Function; import java.util.stream.Collectors;  public class Code {    public static void main(String[] args) {      List<String> listOfString = Arrays.asList("Java", "C", "C++", "Go",         "JavaScript", "Python", "Scala");     System.out.println("input listing of String: " + listOfString);      // Example 1 - converting Stream to List using collect() method     List<String> listOfStringStartsWithJ                               = listOfString.stream()                                             .filter(s -> s.startsWith("J"))                                             .collect(Collectors.toList());      System.out.println("list of String starts amongst alphabetic quality J: "         + listOfStringStartsWithJ);      // Example 2 - converting Stream to Set     Set<String> setOfStringStartsWithC                        = listOfString.stream()                                     .filter(s -> s.startsWith("C"))                                     .collect(Collectors.toSet());      System.out.println("set of String starts amongst alphabetic quality C: "         + setOfStringStartsWithC);      // Example iii - converting Stream to Map     Map<String, Integer> stringToLength                            = listOfString.stream()                                          .collect(Collectors.toMap(Function.identity(),                                                                     String::length));     System.out.println("map of string together with their length: " + stringToLength);      // Example - Converting Stream to Collection e.g. ArrayList     ArrayList<String> stringWithLengthGreaterThanTwo                         = listOfString.stream()                                       .filter(s -> s.length() > 2)                                       .collect(Collectors.toCollection(ArrayList::new));     System.out.println("collection of String amongst length greather than 2: "         + stringWithLengthGreaterThanTwo);    } }  Output input list of String:  [Java, C, C++, Go, JavaScript, Python, Scala] list of String starts with alphabetic quality J:  [Java, JavaScript] set of String starts with alphabetic quality C:  [C++, C] map of string and their length:  {Java=4, C++=3, C=1, Scala=5, JavaScript=10, Go=2, Python=6} collection of String with length greather than 2:  [Java, C++, JavaScript, Python, Scala]



That's all most how to job the collect() method of Stream shape inward Java 8. Along amongst collect(), yous tin job the Collectors method to convert Stream to List, Set, Map, or whatever other Collection of your choice. Just explore the Collectors Javadoc to acquire to a greater extent than most those methods.

Further Learning
The Complete Java MasterClass
Java 8 New Features inward Simple Way
example)
  • How to job filter() method inward Java 8 (tutorial)
  • 5 Free Courses to acquire Java 8 together with ix (courses)
  • How to job Stream shape inward Java 8 (tutorial)
  • How to job forEach() method inward Java 8 (example)
  • 20 Examples of Date together with Time inward Java 8 (tutorial)
  • 5 Books to Learn Java 8 from Scratch (books)
  • How to convert List to Map inward Java 8 (solution)
  • How to job peek() method inward Java 8 (example)
  • Difference betwixt abstract shape together with interface inward Java 8? (answer)
  • 10 Free Courses for Experienced Java Programmers (courses)
  • How to job peek() method inward Java 8 (example)
  • How to sort the may yesteryear values inward Java 8? (example)
  • How to format/parse the engagement amongst LocalDateTime inward Java 8? (tutorial)
  • Top v Java 8 Tutorials for Programmers (courses)
  • Thanks for reading this article so far. If yous similar this Java 8 Stream tutorial so delight part amongst your friends together with colleagues. If yous conduct keep whatever questions or feedback so delight drib a note.

    P. S. - If yous dearest to acquire from costless courses, hither is a collection of free online courses to acquire Java 8 together with Java 9 features on freeCodeCamp.

    No comments:

    Post a Comment