Java 8 streams examples

  1. Working With Maps Using Streams
  2. Java Streams By Example
  3. A Guide to Streams: In
  4. 6 Most Useful Java 8 Stream Functions with Real
  5. Guide to Java 8 Collectors
  6. Java 8 Streams: Definitive Guide to flatMap()
  7. Guide to Java 8 groupingBy Collector
  8. Understanding Java 8 Streams using examples
  9. Java Stream anyMatch() with Examples
  10. Functional Interfaces in Java 8


Download: Java 8 streams examples
Size: 39.41 MB

Working With Maps Using Streams

In this tutorial, we'll discuss some examples of how to use Streams to work with Map data structure, but we're interested here in a functional approach. First, we'll explain the basic idea we'll be using to work with Maps and Streams. Then we'll present a couple of different problems related to Maps and their concrete solutions using Streams. The principal thing to notice is that Streams are sequences of elements which can be easily obtained from a Collection. Maps have a different structure, with a mapping from keys to values, without sequence. However, this doesn't mean that we can't convert a Map structure into different sequences which then allow us to work in a natural way with the Stream API. Let's see ways of obtaining different Collections from a Map, which we can then pivot into a Stream: Map someMap = new HashMap(); We can obtain a set of key-value pairs: Set> entries = someMap.entrySet(); We can also get the key set associated with the Map: Set keySet = someMap.keySet(); Or we could work directly with the set of values: 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(); 3. Getting a Map‘s Keys Using Streams Map books = new HashMap(); books.put( "978-0201633610", "Design patterns : elements of reusable object-oriented software"); books.put( "978-1617291999", "Java 8 ...

Java Streams By Example

In this blog, we are going to take a closer look at the Java 8 Streams API. We will mainly do so by means of examples. We will cover many operations and after reading this blog, you will have a very good basic understanding of the Streams API. Enjoy reading! 1. Introduction The Streams API has been introduced in Java 8 and has been part of the Java language specification for several years by now. Nevertheless, it might be that Streams seem a bit magical to you. Therefore, we will cover the basic concepts of Streams and explain them with some examples. It all starts with the java.util.stream package. The offical Java documentation for this package which contains some good reference documentation, can be found • Streams do not store data. Instead, they are a source for data. • Streams are functional in nature and this is probably why Streams are difficult to comprehend for most people. They produce a result, e.g. like a sum or a new Stream. • Streams are lazyness seeking. Operations can be intermediate or terminal. We will cover both in the next sections. Intermediate operations are always lazy. E.g. find the first occurrence of an element in the Stream. It is not necessary to inspect all elements of the Stream. Once the first occurrence has been found, the search can be ended. • Possibly unbounded. As long as the Stream produces data, the Stream will not end. • The elements of a Stream can only be visited once, just like an Iterator. In the next sections we will cover how t...

A Guide to Streams: In

The addition of the Stream is one of the major new functionality in Java 8. This in-depth tutorial is an introduction to the many functionalities supported by streams, with a focus on simple, practical examples. To understand this material, you need to have a basic, working knowledge of Java 8 (lambda expressions, method references). Introduction First of all, Java 8 Streams should not be confused with Java I/O streams (ex: FileInputStream etc); these have very little to do with each other. Simply put, streams are wrappers around a data source, allowing us to operate with that data source and making bulk processing convenient and fast. A stream does not store data and, in that sense, is not a data structure. It also never modifies the underlying data source. This new functionality — Let's now dive into few simple examples of stream creation and usage — before getting into terminology and core concepts. Stream Creation Let's first obtain a stream from an existing array: private static Employee[] arrayOfEmps = getPalindrome() works on the stream, completely unaware of how the stream was generated. This also increases code reusability and simplifies unit testing. Conclusion In this article, we focused on the details of the new Stream functionality in Java 8. We saw various operations supported and how lambdas and pipelines can be used to write concise code. We also saw some characteristics of streams like lazy evaluation, parallel and infinite streams. You can continue your ...

6 Most Useful Java 8 Stream Functions with Real

Table of Contents • • • • • • • • • • • • • • • • • • What is Stream? A Stream in Java can be defined as a sequence of elements from a source that supports aggregate operations on them. The source here refers to a Collections or Arrays that provides data to a Stream. Stream keeps the ordering of the data as it is in the source. In simple terms, Java streams represent a pipeline through which the data will flow and the functions to operate on the data. Stream Operations Stream operations are divided into intermediate and terminal operations and are combined to form stream pipelines. Intermediate Operation Intermediate operations are always lazy and return a new stream that, when traversed, contains the elements of the initial stream that match the given predicate. Moreover, the traversal of the pipeline source does not begin until the terminal operation of the pipeline is executed. So, executing an intermediate operation such as filter() does not actually perform any filtering, but instead creates a new stream List of Intermediate Operations map(), filter(), distinct(), sorted(), limit(), skip() Terminal Operation Terminal operations, such as Stream.forEach or IntStream.sum, may traverse the stream to produce a result or a side-effect. After the terminal operation is performed, the stream pipeline is considered consumed, and can no longer be used. If you need to traverse the same data source again, you must return to the data source to get a new stream. In almost all cases,...

Guide to Java 8 Collectors

Stream.collect() is one of the Java 8's Stream API‘s terminal methods. It allows us to perform mutable fold operations (repackaging elements to some data structures and applying some additional logic, concatenating them, etc.) on data elements held in a Stream instance. The strategy for this operation is provided via the Collector interface implementation. All predefined implementations can be found in the Collectors class. It's common practice to use the following static import with them to leverage increased readability: import static java.util.stream.Collectors.*; We can also use single import collectors of our choice: import static java.util.stream.Collectors.toList; import static java.util.stream.Collectors.toMap; import static java.util.stream.Collectors.toSet; In the following examples, we'll be reusing the following list: List givenList = Arrays.asList("a", "bb", "ccc", "dd"); 3.1. Collectors.toList() The toList collector can be used for collecting all Stream elements into a List instance. The important thing to remember is that we can't assume any particular List implementation with this method. If we want to have more control over this, we can use toCollection instead. Let's create a Stream instance representing a sequence of elements, and then collect them into a List instance: List result = givenList.stream() .collect(toList()); 3.1.1. Collectors.toUnmodifiableList() Java 10 introduced a convenient way to accumulate the Stream elements into an List: List result...

Java 8 Streams: Definitive Guide to flatMap()

Introduction Mapping elements from one collection to another, applying a transformative function between them is a fairly common and very powerful operation. Java's functional API supports both map() and flatMap(). If you'd like to read more about map(), read our The flatMap() operation is similar to map(). However, flatMap() flattens streams in addition to mapping the elements in those streams. Flat mapping refers to the process of flattening a stream or collection from a nested/2D stream or collection into their 1D representation: List of lists: [[1, 2, 3], [4, 5, 6, 7]] Flattened list: [1, 2, 3, 4, 5, 6, 7] For example, let us say we have a collection of words: Stream words = Stream.of( "lorem", "ipsum", "dolor", "sit", "amet" ); And, we want to generate a list of all the Character objects in those words. We could create a stream of letters for each word and then combine these streams into a single stream of Character objects. First, let's try using the map() method. Since we want to chain two transformative functions, let's define them upfront instead of anonymously calling them as Lambda Expressions: // The member reference replaces `word -> word.chars()` lambda Function intF = CharSequence::chars; This function accepts a String and returns an IntStream - as indicated by the types we've passed in. It transforms a string into an IntStream. Now, we can take this stream and convert the integer values into Character objects. To convert a primitive value to an object - we ...

Guide to Java 8 groupingBy Collector

The Java 8 Stream API lets us process collections of data in a declarative way. The static factory methods Collectors.groupingBy() and Collectors.groupingByConcurrent() provide us with functionality similar to the ‘ GROUP BY' clause in the SQL language. We use them for grouping objects by some property and storing results in a Map instance. The overloaded methods of groupingBy are: • First, with a classification function as the method parameter: static Collector>> groupingBy(Function classifier) • Secondly, with a classification function and a second collector as method parameters: static Collector> groupingBy(Function classifier, Collector downstream) • Finally, with a classification function, a supplier method (that provides the Map implementation which contains the end result), and a second collector as method parameters: static > Collector groupingBy(Function classifier, Supplier mapFactory, Collector downstream) 2.1. Example Code Setup To demonstrate the usage of groupingBy(), let's define a BlogPost class (we will use a stream of BlogPost objects): class BlogPost 2.2. Simple Grouping by a Single Column We use the value returned by the function as a key to the map that we get from the groupingBy collector. To group the blog posts in the blog post list by their type: Map> postsPerType = posts.stream() .collect(groupingBy(BlogPost::getType)); 2.3. groupingBy with a Complex Map Key Type The classification function is not limited to returning only a scalar or String va...

Understanding Java 8 Streams using examples

The section is divided into following sections- • What are Java Streams. • Streams and Collections. • Generate Streams from other DataStructures. • Convert Streams to Other DataStructures. • Various Stream operations. • Intermediate Operations. • Terminal Operations. What are Java Streams? Consider you have a sequence of elements 1,2,3,4,5,6,7,8,9,10 and you have to find the maximum of these numbers. In traditional Java prior to java 8 we will have to write a for loop and then write logic to get the largest of these numbers. Whereas in SQL similar work can be done by writing a simple query SELECT max(numId) from employee Here we just declare what we want and not specify the how to do it. From Java 8 we can achieve something similar using Streams. Java 8 has introduced the java.util.stream which allows users to process sequence of elements. So what does one mean by processing of elements? By processing means performing operations like filter, map, limit, reduce, find, match etc. Streams and Collections- We make use of Streams or Collections when we have to work on sequence of elements. Collections are in-memory data structures which holds elements. These elements are to be computed before they actually are added to the Collections. Conversely Streams are fixed data structures where elements are computed only when required . So it can be viewed that collections have elements computed eagerly, while Streams have elements computed lazily. Generate Streams from other DataStruct...

Java Stream anyMatch() with Examples

• • • • 1. Stream anyMatch() API 1.1. Syntax Here predicate a non-interfering, stateless Predicate to apply to elements of the stream. The anyMatch() method returns true if at least one element satisfies the condition provided by predicate, else false. boolean anyMatch(Predicate predicate) 1.2. Description • It is a short-circuiting terminal operation. • It returns whether any elements of this stream match the provided predicate. • May not evaluate the predicate on all elements if not necessary for determining the result. Method returns true as soon as first matching element is encountered. • If the stream is empty then false is returned and the predicate is not evaluated. • The difference between allMatch() and anyMatch() is that anyMatch() returns true if any of the elements in a stream matches the given predicate. When using allMatch(), all the elements must match the given predicate. 2. Stream anyMatch() Examples Example 1: Checking if Stream contains a Specific Element In this Java example, we are using the anyMatch() method to check if the stream contains the string "four". As we see that the stream contains the string, so the output of the example is true. Stream stream = Stream.of("one", "two", "three", "four"); boolean match = stream.anyMatch(s -> s.contains("four")); System.out.println(match); Program output. true Example 2: Stream.anyMatch() with Multiple Predicates To satisfy multiple conditions, create a composed predicate with two or more simple predicates. I...

Functional Interfaces in Java 8

Java 8 brought a powerful new syntactic improvement in the form of lambda expressions. A lambda is an anonymous function that we can handle as a first-class language citizen. For instance, we can pass it to or return it from a method. Before Java 8, we would usually create a class for every case where we needed to encapsulate a single piece of functionality. This implied a lot of unnecessary boilerplate code to define something that served as a primitive function representation. The article java.util.function package. 3. Functional Interfaces Any interface with a SAM(Single Abstract Method) is a functional interface, and its implementation may be treated as lambda expressions. Note that Java 8's default methods are not abstract and do not count; a functional interface may still have multiple default methods. We can observe this by looking at the Function's 4. Functions The most simple and general case of a lambda is a functional interface with a method that receives one value and returns another. This function of a single argument is represented by the Function interface, which is parameterized by the types of its argument and a return value: public interface Function One of the usages of the Function type in the standard library is the Map.computeIfAbsent method. This method returns a value from a map by key, but calculates a value if a key is not already present in a map. To calculate a value, it uses the passed Function implementation: Map nameMap = new HashMap(); Inte...