10 Examples Of Flow Inwards Coffee Viii - Count + Filter + Map + Distinct + Collect

The Java 8 unloosen of Java Programming linguistic communication was a game changer version. It non exclusively provided to a greater extent than or less useful method but totally changed the way you lot write programs inward Java. The most of import alter it brings inward the mindset of Java developers was to shout upwards functional as well as supported that past times providing fundamental features similar lambda facial expression as well as Stream API, which takes wages of parallel processing as well as functional operations similar filter, map, flatMap etc. Since hence a lot of Java developers are trying their hands to larn those major changes similar lambda expression, method reference, novel Date as well as Time classes, as well as to a greater extent than importantly, Stream API for mass information operations.

In my opinion, the best way to larn whatsoever novel characteristic or functionality is past times writing curt examples as well as agreement them inward depth. I learned that way as well as that's what prompts me to write this article. In this Java 8 tutorial, I guide maintain shared to a greater extent than or less uncomplicated examples of java.util.Stream package, which you lot tin utilisation inward your day-to-day Java programming tasks.

Streams are 1 of the most of import additions on JDK, it allows you lot to leverage other changes similar lambda expression, method reference, functional interface as well as internal iteration introduced via the forEach() method.

Some of the most mutual things nosotros practice amongst Streams are filtering a collection, applying map as well as trim down role on all elements of the collection as well as taking wages of lazy evaluation, built-in parallelism via parallelStream().

This is past times no agency a consummate fix of examples you lot demand to original Java 8 Stream API, but it volition innovate amongst fundamental functions as well as encourage you lot to explore past times yourself past times reading Java documentation as well as trying them. You tin every bit good banking concern check out a comprehensive online course of didactics similar The Java MasterClass to larn them inward depth along amongst other Java 8 changes.





1. How to utilisation Streams inward Java 8

You tin utilisation Streams to practice a lot of things inward Java 8. By the way, this current is a fleck unlike than your Java IO streams e.g. InputStream and OutputStream. This current provides an elegant lazy evaluation of an expression, as well as it every bit good supports intermediate as well as end operations.

Terminal operations are used to create a consequence as well as afterward that, you lot cannot reuse them.

The expert affair nearly Streams is that they exit source collection intact i.e. operations on streams doesn't impact the collection from which streams are obtained. By the way, you lot tin acquire Stream non only from the Collection but from other sources similar Random Number generator as well as FileInputStream.

In fact, current API is a handy abstraction for working amongst aggregated data, peculiarly when nosotros demand to perform multiple actions, such every bit transforming the content, apply to a greater extent than or less filters as well as maybe grouping them past times a property.

Since the collection is going to live the starting indicate for a stream, I guide maintain used List for all my examples. Once you lot know basics, you lot tin every bit good apply it to other Collection classes e.g. HashSet or HashMap.


Now let's run across the code as well as hence nosotros volition verbalize nearly each example.

import java.util.Arrays; import java.util.IntSummaryStatistics; import java.util.List; import java.util.stream.Collectors;  /**   * Java plan to demonstrate how to utilisation Java 8 Stream API amongst simple   * examples similar filter objects, transforming objects as well as creating subsets.   * @author http://java67.com   */ public class Java8Streams{      public static void main(String args[]) {          // Count the empty strings         List<String> strList = Arrays.asList("abc", "", "bcd", "", "defg", "jk");         long count = strList.stream()                             .filter(x -> x.isEmpty())                             .count();         System.out.printf("List %s has %d empty strings %n", strList, count);          // Count String amongst length to a greater extent than than 3         long num = strList.stream()                            .filter(x -> x.length()> 3)                            .count();         System.out.printf("List %s has %d strings of length to a greater extent than than 3 %n",                              strList, num);                     // Count publish of String which startswith "a"         count = strList.stream()                        .filter(x -> x.startsWith("a"))                        .count();         System.out.printf("List %s has %d strings which startsWith 'a' %n",                                strList, count);               // Remove all empty Strings from List         List<String> filtered = strList.stream()                                        .filter(x -> !x.isEmpty())                                        .collect(Collectors.toList());         System.out.printf("Original List : %s, List without Empty Strings : %s %n",                                        strList, filtered);               // Create a List amongst String to a greater extent than than 2 characters         filtered = strList.stream()                           .filter(x -> x.length()> 2)                           .collect(Collectors.toList());         System.out.printf("Original List : %s, filtered listing : %s %n", strList, filtered);                     // Convert String to Uppercase as well as bring together them using coma         List<String> G7 = Arrays.asList("USA", "Japan", "France", "Germany", "Italy",                                            "U.K.","Canada");         String G7Countries = G7.stream()                                .map(x -> x.toUpperCase())                                .collect(Collectors.joining(", "));         System.out.println(G7Countries);               // Create List of foursquare of all distinct numbers         List<Integer> numbers = Arrays.asList(9, 10, 3, 4, 7, 3, 4);         List<Integer> distinct = numbers.stream()                                          .map( i -> i*i).distinct()                                          .collect(Collectors.toList());         System.out.printf("Original List : %s,  Square Without duplicates : %s %n",                                           numbers, distinct);               //Get count, min, max, sum, as well as average for numbers         List<Integer> primes = Arrays.asList(2, 3, 5, 7, 11, 13, 17, 19, 23, 29);         IntSummaryStatistics stats = primes.stream()                                            .mapToInt((x) -> x)                                            .summaryStatistics();         System.out.println("Highest prime publish inward List : " + stats.getMax());         System.out.println("Lowest prime publish inward List : " + stats.getMin());         System.out.println("Sum of all prime numbers : " + stats.getSum());         System.out.println("Average of all prime numbers : " + stats.getAverage());     }  }  Output: List [abc, , bcd, , defg, jk] has 2 empty strings List [abc, , bcd, , defg, jk] has 1 strings of length to a greater extent than than 3 List [abc, , bcd, , defg, jk] has 1 strings which startsWith 'a' Original List : [abc, , bcd, , defg, jk], List without Empty Strings : [abc, bcd, defg, jk] Original List : [abc, , bcd, , defg, jk], filtered listing : [abc, bcd, defg] USA, JAPAN, FRANCE, GERMANY, ITALY, U.K., CANADA Original List : [9, 10, 3, 4, 7, 3, 4],  Square Without duplicates : [81, 100, 9, 16, 49] Highest prime publish inward List : 29 Lowest prime publish inward List : 2 Sum of all prime numbers : 129 Average of all prime numbers : 12.9


2. Java 8 Stream Examples

Now that you lot guide maintain seen the code inward action, you lot may guide maintain figured out that nosotros guide maintain used a lot of methods from the Stream course of didactics of Java 8 API.

Some of the most prominent methods used inward these examples are the filter() -  which allows elements which tally the predicate, count() - which counts the publish of elements inward a stream, map() - which applies a role inward each chemical ingredient of Stream for transformation, as well as collect() - which collects the concluding consequence of Stream processing into a Collection.

Now, let's walk through each illustration to sympathize what they are doing as well as how they are doing.

1. Java 8 Filter Example: Counting Empty String

Here is an illustration of counting how many elements are inward the current at whatsoever phase of pipeline processing using count() method of Stream class.

List<String> strList = Arrays.asList("abc", "", "bcd", "", "defg", "jk"); long count = strList.stream()                      .filter(x -> x.isEmpty())                      .count();

This is a expert illustration is to demonstrate how you lot tin filter surely object from Collection as well as practice a subset of elements which satisfy given criterion. In minute line strList.stream() returns a Stream as well as hence nosotros use the filter() method, which accepts a Predicate.

Since the java.util.function.Predicate is a functional interface ( an interface amongst only 1 abstract method), nosotros tin overstep lambda facial expression instead of an instance of the Predicate interface. Here nosotros tin define code to specify a condition.

This code volition locomote to the test() method of Predicate as well as volition live applied to each chemical ingredient during internal iteration. All Strings which are empty are counted by count() method, which is a end operation.

After this line, you lot tin non telephone telephone whatsoever method on this Stream. Remember filter() is a tricky method, it does non filter chemical ingredient from the original collection, instead, it selects chemical ingredient which satisfies criterion as well as returns them inward novel Collection.

You tin read to a greater extent than nearly that inward this excellent type inference, that's why in 1 lawsuit you lot specify type parameter inward List, no demand to declare it again, Java 8 volition infer it from there.

This is the argue you lot tin telephone telephone all method of java.lang.String on variable x, whose type was non declared within lambda expression.


3. Java 8 Filter Example 3: Count publish of String which starts amongst "a"

This illustration is every bit good just similar to the previous 2 examples, the exclusively affair which is unlike is the status nosotros are passing to filter method. In the outset example, nosotros filter empty string, inward the minute illustration nosotros filter string whose length has to a greater extent than than five characters as well as inward this example, nosotros are filtering String which starts amongst the missive of the alphabet "a".

By doing all 3 examples, you lot should experience to a greater extent than comfortable with the filter() method. 

long count = strList.stream()                     .filter(x -> x.startsWith("a"))                     .count();



This is immediately the touchstone technique to filter elements inward Java Collection. You tin specify arbitrary whatsoever status on lambda facial expression to declare filtering logic.

For example, inward this code, nosotros are creating a subset of String which is starting amongst "a" as well as hence counting them past times using count() method.  If you lot are non familiar amongst basic String materials as well as Java Collection framework, I advise you lot to outset locomote through The Complete Java MasterClass on Udemy, 1 of the best course of didactics to larn Java. It is every bit good updated for Java xi recently.

 unloosen of Java Programming linguistic communication was a game changer version 10 Examples of Stream inward Java 8 - count + filter + map + distinct + collect



4. Java 8 Collectors Example: Remove all empty Strings from List

Now, this illustration is a footling fleck unlike than the previous three. Here nosotros are in 1 lawsuit again using filter() method to practice a subset of all string which is non-empty but instead of counting, nosotros are immediately calling static utility method Collectors.toList() to render them every bit List. 

List<String> filtered = strList.stream()                                .filter(x -> !x.isEmpty())                                .collect(Collectors.toList());

The Collectors course of didactics is really similar to the java.util.Collections class, total of static methods, which you lot tin utilisation along amongst Collection. You tin twine filtered elements into a Set or List past times using Collectors class.



5. Java 8 Collectors Example 2: Create a List amongst String to a greater extent than than 2 characters

In this example, ware in 1 lawsuit again using the filter() method as well as Collectors class, but our filtering criterion is different. 

List<String> filtered = strList.stream()                                .filter(x -> x.length()> 2)                                .collect(Collectors.toList());

After doing this example, you lot should live comfortable amongst creating a subset from the original collection.




6. Java 8 Map functional Example: Convert String to working capital missive of the alphabet as well as Join them amongst coma

So far nosotros guide maintain seen examples of only filter() method, inward this example, nosotros volition larn how to use map() function. 

List<String> G7 = Arrays.asList("USA", "Japan", "France", "Germany",                                         "Italy", "U.K.","Canada"); String G7Countries = G7.stream()                        .map(x -> x.toUpperCase())                        .collect(Collectors.joining(", ")); 

This is similar to the Map concept of functional programming paradigm, similar hither nosotros are converting each String to upper illustration as well as hence lastly nosotros guide maintain joined all String using the Collectors.joining(",") method, to a greater extent than or less other utility method from Java 8 which tin bring together String past times using given delimiter.

If you lot desire to larn to a greater extent than nearly what just has been changed inward Java 8 along amongst lambdas, Stream, as well as functional programming, map() method, hither nosotros are mapping each chemical ingredient to their foursquare as well as hence filtering out all duplicate elements past times calling distinct() method. 

List<Integer> numbers = Arrays.asList(9, 10, 3, 4, 7, 3, 4); List<Integer> distinct = numbers.stream()                                 .map( i -> i*i)                                 .distinct()                                 .collect(Collectors.toList());

Finally past times using the collect() method nosotros are gathering output into a List.




8. Java 8 Statistics Example: Get count, min, max, sum, as well as the average for numbers

This our concluding illustration of Stream API, inward this illustration nosotros volition larn how to acquire to a greater extent than or less statistical information from Collection e.g. finding the minimum or maximum publish from List, calculating the total of all numbers from a numeric listing or calculating the average of all numbers cast List. 

List<Integer> primes = Arrays.asList(2, 3, 5, 7, 11, 13, 17, 19, 23, 29); IntSummaryStatistics stats = primes.stream()                                    .mapToInt((x) -> x)                                    .summaryStatistics();

Since this statistics operations are numeric inward nature, it's of import to telephone telephone mapToInt() method. After this, nosotros telephone telephone the summaryStatistics(), which returns an instance of an IntSummaryStatistics.

It is this object which provides us utility method similar getMin(), getMax(), getSum() or getAverage().

By using these full general purpose methods, you lot tin easily practice a lot of things which require a lot of code earlier Java 8.


That's all nearly how to utilisation Stream API inward Java 8. I guide maintain barely scratched the surface amongst these examples, streams guide maintain several gems to offer. At really minimum, every Java developer immediately should know nearly filtering elements as well as applying map role to transform them. For farther reading, you lot tin start exploring java.util.stream packet as well as java.util.function package. These 2 packages guide maintain a lot of interesting things to offer.


Further Learning
The Complete Java MasterClass
The Ultimate Java 8 Tutorial
Refactoring to Java 8 Streams as well as Lambdas Online Self- Study Workshop
Top five Java 8 Courses for Programmers
10 Things Java Developers Should Lear inward 2019
10 Tips to locomote a meliorate Java Developer
10 New Features of Java 10 Programmer Should Know
10 DevOps Courses for Java Developers

P.S.: If you lot desire to larn to a greater extent than nearly novel features inward Java 8 hence delight run across the tutorial What's New inward Java 8. It explains all the of import features of Java 8 e.g. lambda expressions, streams, functional interface, Optional, novel Date as well as Time API as well as other miscellaneous changes.

0 Response to "10 Examples Of Flow Inwards Coffee Viii - Count + Filter + Map + Distinct + Collect"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel