Pages

Showing posts with label Java 8. Show all posts
Showing posts with label Java 8. Show all posts

Friday, January 7, 2022

Java 8 - How to convert Calendar to LocalDateTime?

1. Overview

In this article, You'll learn how to convert Calendar to LocalDateTime object in java 8 DateTime api

LocalDateTime api can be used completely replacement to the Date class as all features of Date functions are done in a simple and precise way such as adding minutes to the current date.

Java 8 - How to convert Calendar to LocalDateTime?

Friday, December 31, 2021

Java 8 Default and Static Methods - Interface New Concepts

1. Overview


In this Java 8 new concept, We are going to learn today what is the Default Method in Java 8 and why it is introduced in java 8 changes.

Java 8 introduces a new concept of default method implementation in interfaces. This capability is added for backward compatibility so that old interfaces can be used to leverage the lambda expression capability of Java 8. For example, the List interface is not having the forEach() method. If they add this method as an abstract method then all List implementation classes must have to provide the implementation since it is common functionality to iterate the list. So they had to introduce this concept to enhance features and support for the backward classes.

Java 8 Default and Static Methods

Java 8 Nashorn Javascript With Examples

1. Overview

In this tutorial, you will learn how to use javascript in java and how to integrate them with each other.

Usage of javascript in java can be done with the newly added Nashorn JavaScript engine in java 8.

This completely replaces the old version of the Rhino javascript engine and it gives 2 to 10 times better performance than the older one because it does the code compilation in memory and passes the byte code to the JVM directly.

And also it uses the dynamic loading feature is introduced in java 7 to enhance the performance and completely replaces the Rhino Engine.

Java 8 Nashorn Javascript


Let us start writing the examples using the code from the command line, java, and javascript code.

Note: Before using jjs tool,  you should remember that "The jjs tool is planned to be removed from a future JDK release"

2. Nashorn jjs - Command-Line Engine

JDK 1.8 is equipped with the command line interpreter that is called "jjs". jjs is used to run the javascript files as below.

jjs tool can be found at the location $JAVA_HOME/bin

jjs> jjs first_script.js

And also jjs can be used as interactive shells such as REPL. To start a REPL, do not pass any arguments to it.

javprogramto-MacBook-Pro-2$ jjs
Warning: The jjs tool is planned to be removed from a future JDK release
jjs> 
jjs> 

You can print the content on to console using print() method and it takes string content.

jjs> print("Hello World")
Hello World
jjs> print("welocome to javaprogramto.com blog for java 8 tutorial")
welocome to javaprogramto.com blog for java 8 tutorial
jjs> 

3. Running js file as a shell script

As you run the shell script file from the command line like "./hello.sh" in a similar way you can run the javascript file. 

Just add bang pointing to jjs location "#!$JAVA_HOME/bin/jjs"

Let us write a simple code and save it as hello.js file.

#!$JAVA_HOME/bin/jjs
var greeting = "Hello World, Welcome";
print(greeting);

Now, run this script from the command line with "./hello.js" and observe the below output.

$ ./hello.js
Warning: The jjs tool is planned to be removed from a future JDK release
Hello World, Welcome
$ 

Like this, you can use java code from the js file also. In the next, sections you will understand how to use java code in javascript files.

4. Passing Arguments to JJS

jjs command can work with the arguments also. When you use jjs command to start the interactive mode, you can pass as many as arguments you need.

And all of the passed arguments are stored in a variable "arguments". By using this builtin keyword in javascript, you can get all of these argument values.

Note: You need to pass the double hyphen "--" after jjs command.

Let us run the sample code as "jjs -- one two threee"

Arguments Example:

$ jjs -- one two threee
Warning: The jjs tool is planned to be removed from a future JDK release
jjs> print("given  argument  values are "+arguments.join(" , "))
given  argument  values are one , two , threee
jjs>$ 

5. Call JavaScript from Java

Java 8 api is added with a built-in engine that is called an Embedded Script Engine which creates a runtime environment to execute the javascript code on the JVM for a dynamic language.

Use ScriptEngineManager class to get the script engines that are managed by JVM.

Next, get the nashorn script engine using getEngineByName("nashorn") and pass the right name to it.

Finally, call eval() method to run the native javascript code from java and eval() returns an Object if you are executing arithmetic operations. In such cases, you need to use explicit type casting to the right object types. It is the time now to play with the javascript notations.

package com.javaprogramto.java8.nashorn;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

public class CallJavaScriptFromJavaExample {

    public static void main(String[] args) throws ScriptException {

        // creating java script engine
        ScriptEngineManager scriptEngineManager = new ScriptEngineManager();

        // getting the nashorn engine
        ScriptEngine nashorn = scriptEngineManager.getEngineByName("nashorn");

        // evaluating the javascript statement  to  print
        nashorn.eval("print('hello , this is first javascript example in java') ");

        // summing 2  numbers in  js  from  java code.
        Integer i = (Integer) nashorn.eval("1 + 2");
        
        System.out.println("sum from javascript : " + i);
    }
}
 

Output:

hello , this is first javascript example in java
sum from javascript : 3
 

You can observe the output that printed the content using the javascript print() method and the addition of two numbers.

6. Exceptions  from NashornScriptEngine

If you pass the invalid or wrong javascript syntax to eval() method then. it will throw a runtime exception saying "ScriptException" with different reasons.

If you miss the ending or closing quotes. for the print() method then it. will say "<eval> Missing close quote"

 Warning: Nashorn engine is planned to be removed from a future JDK release
 Exception in thread "main" javax.script.ScriptException: <eval>:1:57 Missing close quote
 pirnt('hello , this is first javascript example in java) 
                                                          ^ in <eval> at line number 1 at column number 57
 	at jdk.scripting.nashorn/jdk.nashorn.api.scripting.NashornScriptEngine.throwAsScriptException(NashornScriptEngine.java:477)
 	at jdk.scripting.nashorn/jdk.nashorn.api.scripting.NashornScriptEngine.compileImpl(NashornScriptEngine.java:544)
 	at jdk.scripting.nashorn/jdk.nashorn.api.scripting.NashornScriptEngine.compileImpl(NashornScriptEngine.java:531)
 	at jdk.scripting.nashorn/jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:409)
 	at jdk.scripting.nashorn/jdk.nashorn.api.scripting.NashornScriptEngine.eval(NashornScriptEngine.java:162)
 	at java.scripting/javax.script.AbstractScriptEngine.eval(AbstractScriptEngine.java:264)
 	at com.javaprogramto.java8.nashorn.CallJavaScriptFromJavaExample.main(CallJavaScriptFromJavaExample.java:16)
 Caused by: jdk.nashorn.internal.runtime.ParserException: <eval>:1:57 Missing close quote
 pirnt('hello , this is first javascript example in java) 
                                                          ^
 	at jdk.scripting.nashorn/jdk.nashorn.internal.parser.Lexer.error(Lexer.java:1860)
 	at jdk.scripting.nashorn/jdk.nashorn.internal.parser.Lexer.scanString(Lexer.java:1006)
 	at jdk.scripting.nashorn/jdk.nashorn.internal.parser.Lexer.lexify(Lexer.java:1717)
 	at jdk.scripting.nashorn/jdk.nashorn.internal.parser.AbstractParser.getToken(AbstractParser.java:135)
 	at jdk.scripting.nashorn/jdk.nashorn.internal.parser.AbstractParser.nextToken(AbstractParser.java:216)
 	at jdk.scripting.nashorn/jdk.nashorn.internal.parser.AbstractParser.nextOrEOL(AbstractParser.java:173)
 	at jdk.scripting.nashorn/jdk.nashorn.internal.parser.AbstractParser.next(AbstractParser.java:160)
 	at jdk.scripting.nashorn/jdk.nashorn.internal.parser.Parser.scanFirstToken(Parser.java:293)
 	at jdk.scripting.nashorn/jdk.nashorn.internal.parser.Parser.parse(Parser.java:323)
 	at jdk.scripting.nashorn/jdk.nashorn.internal.parser.Parser.parse(Parser.java:285)
 	at jdk.scripting.nashorn/jdk.nashorn.internal.runtime.Context.compile(Context.java:1500)
 	at jdk.scripting.nashorn/jdk.nashorn.internal.runtime.Context.compileScript(Context.java:1467)
 	at jdk.scripting.nashorn/jdk.nashorn.internal.runtime.Context.compileScript(Context.java:750)
 	at jdk.scripting.nashorn/jdk.nashorn.api.scripting.NashornScriptEngine.compileImpl(NashornScriptEngine.java:542)
 	... 5 more
 

If you pass the invalid method name then it will give an error.

nashorn.eval("invoke(10, 20)");
 

Error:

Warning: Nashorn engine is planned to be removed from a future JDK release
Exception in thread "main" javax.script.ScriptException: ReferenceError: "invoke" is not defined in <eval> at line number 1
	at jdk.scripting.nashorn/jdk.nashorn.api.scripting.NashornScriptEngine.throwAsScriptException(NashornScriptEngine.java:477)
	at jdk.scripting.nashorn/jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:461)
	at jdk.scripting.nashorn/jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:413)
	at jdk.scripting.nashorn/jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:409)
	at jdk.scripting.nashorn/jdk.nashorn.api.scripting.NashornScriptEngine.eval(NashornScriptEngine.java:162)
	at java.scripting/javax.script.AbstractScriptEngine.eval(AbstractScriptEngine.java:264)
	at com.javaprogramto.java8.nashorn.CallJavaScriptFromJavaExample.main(CallJavaScriptFromJavaExample.java:18)
Caused by: <eval>:1 ReferenceError: "invoke" is not defined
	at jdk.scripting.nashorn/jdk.nashorn.internal.runtime.ECMAErrors.error(ECMAErrors.java:57)
	at jdk.scripting.nashorn/jdk.nashorn.internal.runtime.ECMAErrors.referenceError(ECMAErrors.java:319)
	at jdk.scripting.nashorn/jdk.nashorn.internal.runtime.ECMAErrors.referenceError(ECMAErrors.java:291)
	at jdk.scripting.nashorn/jdk.nashorn.internal.objects.Global.__noSuchProperty__(Global.java:1616)
	at jdk.scripting.nashorn.scripts/jdk.nashorn.internal.scripts.Script$Recompilation$1$\^eval\_/0x00000008001dc040.:program(<eval>:1)
	at jdk.scripting.nashorn/jdk.nashorn.internal.runtime.ScriptFunctionData.invoke(ScriptFunctionData.java:655)
	at jdk.scripting.nashorn/jdk.nashorn.internal.runtime.ScriptFunction.invoke(ScriptFunction.java:513)
	at jdk.scripting.nashorn/jdk.nashorn.internal.runtime.ScriptRuntime.apply(ScriptRuntime.java:527)
	at jdk.scripting.nashorn/jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:456)
	... 5 more
 

7. Call Java From JavaScript

In the previous section,  we. have seen how to call native javascript code from java classes. 

Next, let us see how to use java classes in JavaScript files.

Let us create a sample javascript code that uses the java class BigDecimal.

Call Java.type() method to use the java classes from javascript and pass the class name along with the package name. Then that class is loaded into the nashorn engine and returns its object. So, we've stored it in the var variable.

Calling Java Methods from JavaScript Example:

var BigDecimalClass = Java.type('java.math.BigDecimal');

function calculate(amount, percentage) {

    var result = new BigDecimalClass(amount).multiply(new BigDecimalClass(percentage)).divide(
        new BigDecimalClass("100"), 2, BigDecimalimalClass.ROUND_HALF_EVEN);

    return result.toPlainString();
}
var result = calculate(1000,20);
print("Final value : "+result);
 

Output:

$ jjs sample.js 
Final value : 200.00
$ 
 

Any java class can be used inside the javascript code such as adding key-value pairs. to HashMap.

Save the below file as hashmap.js

Example to use HashMap from Javascript:

var HashMap = Java.type('java.util.HashMap')
var map = new HashMap()
map.put('hello', 'world')
print("map values : "+map)
 

Output:

$ jjs hashmap.js 
map values : {hello=world}
$ 
 

8. Conclusion

In this article,  you've seen the new javascript engine nashorn added in java 8.

Examples on how to call javascript from java and vice versa.

Now, you can call javascript functions, pass bindings, and use java objects from both languages using jjs tool.

All examples shown are over GitHub.

Examples of Nashorn engine on GitHub

Removal of Nashorn

ScriptEngine API

Wednesday, December 22, 2021

Java 8 Collectors Examples In Depth

1. Overview


In this tutorial, We'll be learning to Java 8 Collectors API in-depth with all methods and example programs. Collectors is a public final class that extends the Object class.

Read this article completely with patience. You will definitely become a master in Java 8’s Collectors by end of this post.

Collectors class provides various useful reduction operations, such as accumulating elements into collections, summarizing elements according to various criteria, etc

Java 8 Collectors Examples In Depth

Java 8 - Stream Group By - Collectors.GroupingBy() Examples

1. Overview

In this tutorial, We will learn how to perform the groupingby operation in java 8

If you have worked in the Oracle database, you must have seen the group by the operator in many complex SQL queries.

You will learn the following techniques in this lesson.

  • How to java stream group by operation?
  • Java stream group by count?
  • Java 8 stream group by and sort?
  • Java stream group by reduce?
  • java stream group by multiple fields?
  • group by with custom objects?

In a similar way, we can implement the group by clause from java 8 onwards. Java 8 Stream API is added with the data grouping capabilities as part of Collectors api.

Collectors API is to collect the final data from stream operations.

Java 8 - Stream Group By - Collectors.GroupingBy() Examples

Tuesday, December 14, 2021

Java 8 Streams Filter With Multiple Conditions Examples

1. Overview


In this tutorial, We'll learn how to utilise stream filter() with several filter conditions (can be more than one condition).

Normally, we apply a single condition to streams using filter() method with lambda and then store the results in Lists or Sets.

However, we'll learn how to use the filter() method with as many condition filters as we require.

More filters can be applied in a variety of methods, such as using the filter() method twice or supplying another predicate to the Predicate.and() method.

In the next sections, we'll look at examples with single and multiple conditions.

GitHub link is given at the end of the article for the shown examples.

Java 8 Streams Filter With Multiple Conditions Examples



Saturday, December 11, 2021

Java 8 Streams if else logic

1. Overview

In this tutorial, We'll learn how to use if/else statements in java 8 streams.

If you are new to the java 8 stream,  It is recommended to read the in-depth on the basics of java 8 streams.

First, we will see the simple to find the even numbers from the given list of numbers.

Next, we will write the java 8 examples with the forEach() and streams filter() method.

Java 8 Streams if else logic


Friday, December 10, 2021

Java 8 Stream Collect() Examples

1. Overview

In this tutorial, We will learn how to use the Stream.collect() method in Java 8 Stream api.

Many of you know that Stream.collect() method is added as part of the new JDK 8 Streams.

Stream collect() method is used to collect the output of stream operations into the collection such as List, Set or Map. Sometimes we can collect into LinkedList, TreeSet or even into the String.

Additionally, we can perform the group by, partition by operations on the streams with Collect() method.

Let us explore the usages of Stream.collect() method with examples.

Java 8 Stream Collect() Examples



2. Java 8 Stream Collect() to List using Collectors.toList()


The below is the first example using Stream.collect() method on the stream pipe line. First created a stream object using stream() method and converted the each value in the stream to uppercase using word.toUpperCase() method. 

Finally, called the collect() method by passing the Collectors.toList() method which collect the each word from the stream into a List. The returned list is the instance of ArrayList and it is the default collection object created by toList() method.


package com.javaprogramto.java8.collectors.collect;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Examples to Java 8 Stream collect() method
 * 
 * @author JavaProgramTo.com
 *
 */
public class StreamCollectExample {

	public static void main(String[] args) {

		List<String> words = Arrays.asList("hello", "how", "are", "you", "doing", "mate");
		
		List<String> list = words.stream()
				.map(word -> word.toUpperCase())
				.collect(Collectors.toList());
		
		System.out.println("Collectors.toList() : "+list);

	}

}
 
Output:
Collectors.toList() : [HELLO, HOW, ARE, YOU, DOING, MATE]
 

3. Java 8 Stream Collect() to Set using Collectors.toSet()


Furthermore, The below example is to get the numbers length is 3 and remove the duplicates from stream. Finally, collecting the stream output into Set.

And also collected the same output into the List to observe the difference between the toList() and toSet() methods.

toSet() method returns default HashSet object. If you want to get the LinkedHashSet object then you need to use the Collectors.toCollection() method with specifying the LinkedHashSet class.

In the later section of this tutorial, you will learn how to get the different Set object other than default HashSet.

List<String> numbers = Arrays.asList("one", "two", "one", "two", "three", "four");

// using toSet()
Set<String> set = numbers.stream()
 	.filter(number -> number.length() == 3)
	.collect(Collectors.toSet());

// without duplicates
System.out.println("Set removes the duplicates : ");
set.forEach(System.out::println);

// using toList()
List<String> list2 = numbers.stream()
	.filter(number -> number.length() == 3)
	.collect(Collectors.toList());

// without duplicates
System.out.println("List with duplicates: ");
list2.forEach(System.out::println);
 
Output:
Set removes the duplicates : 
one
two
List with duplicates: 
one
two
one
two
 

4. Java 8 Stream Collect() to Map using Collectors.toMap()


Next, In the below example program, we will learn how to convert the stream intermediate output to the Map using Collectors.toMap() method.
List<String> words = Arrays.asList("hello", "how", "are", "you", "doing", "mate");
		
Map<String, Integer> wordsLength = words.stream()
		.collect(Collectors.toMap(Function.identity(), String::length));

System.out.println("toMap() output: ");
wordsLength.forEach((key, value) -> System.out.println(key + " = "+value));
 
Output:
toMap() output: 
how = 3
doing = 5
are = 3
mate = 4
hello = 5
you = 3
Function.identity() is used to get the same object as a key and remember that always identity() method returns the map key when using toMap() method in java 8.

By default, toMap() method returns the HashMap object and if you want TreeMap you can use the overloaded toMap() method as shown in the next section.

If you observe that input list has unique values and Map does not allow the duplicates keys. So what happens if the input has duplicate values as below?
List<String> numbers = Arrays.asList("one", "two", "one", "two", "three", "four");
 
If you run the toMap() logic with the above numbers list with duplicate values then it will through the runtime exception.
Exception in thread "main" java.lang.IllegalStateException: Duplicate key one (attempted merging values 3 and 3)
	at java.base/java.util.stream.Collectors.duplicateKeyException(Collectors.java:133)
	at java.base/java.util.stream.Collectors.lambda$uniqKeysMapAccumulator$1(Collectors.java:180)
	at java.base/java.util.stream.ReduceOps$3ReducingSink.accept(ReduceOps.java:169)
	at java.base/java.util.Spliterators$ArraySpliterator.forEachRemaining(Spliterators.java:948)
	at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:484)
	at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474)
	at java.base/java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:913)
	at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
	at java.base/java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:578)
	at com.javaprogramto.java8.collectors.collect.StreamCollectExample.main(StreamCollectExample.java:45)
 
To work with the duplicate values, we need to use another toMap() overloaded method which takes another 3rd argument that takes care for duplicate keys.

We need to define the logic for duplicate key. If the key is duplicate then add "repeated" string to the value to know that key is repeated,

This the way to handle the duplicate keys with Collectors.toMap() method.
Map<String, String> wordsCount = numbers.stream()
	.collect(Collectors.toMap(Function.identity(), Function.identity(), (oldValue, newValue) -> oldValue+" repeated"));
		
System.out.println("toMap() with dupolicates: ");
wordsCount.forEach((key, value) -> System.out.println(key + " = "+value));
 
Output:
toMap() with duplicates: 
four = four
one = one repeated
three = three
two = two repeated 

5. Java 8 Stream Collect() to Collection such as LinkedList or TreeSet using Collectors.toCollection()


As of now, we have seen toList(), toSet(), toMap() methods and which returns default ArrayList, HashSet, HashMap object as default.

If you want to get the return objects as other collection objects such as LinkedList, LinkedHashSet then use Collectors.toCollection() method.

To cast to TreeMap, you need to use the toMap() method with the Supplier as 4th argument.
// toCollection() examples
// to linkedlist
List<String> linkedList = words.stream()
	.collect(Collectors.toCollection(LinkedList::new));

System.out.println("linkedList is instance of LinkedList = "+(linkedList instanceof LinkedList));

// to linkedhashset
Set<String> linkedhHashSet = words.stream().
	collect(Collectors.toCollection(LinkedHashSet::new));
System.out.println("linkedhHashSet is instance of LinkedHashSet = "+(linkedhHashSet instanceof LinkedHashSet));

// to linkedhashset
Map<String, Integer> treeMap = words.stream()
	.collect(Collectors.toMap(Function.identity(), String::length, (oldValue, newValue) -> newValue, TreeMap::new));
System.out.println("treeMap is instance of TreeMap = "+(treeMap instanceof TreeMap));
	
 
Output:
linkedList is instance of LinkedList = true
linkedhHashSet is instance of LinkedHashSet = true
treeMap is instance of TreeMap = true	
 

6. Java 8 Stream API Collect Full Examples

package com.javaprogramto.java8.collectors.collect;

import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * Examples to Java 8 Stream collect() method
 * 
 * @author JavaProgramTo.com
 *
 */
public class StreamCollectExample {

	public static void main(String[] args) {

		// toList() examples
		List<String> words = Arrays.asList("hello", "how", "are", "you", "doing", "mate");
		
		List<String> list = words.stream()
		.map(word -> word.toUpperCase())
		.collect(Collectors.toList());
		
		System.out.println("Collectors.toList() : "+list);

		
		List<String> numbers = Arrays.asList("one", "two", "one", "two", "three", "four");

		// using toSet()
		Set<String> set = numbers.stream().filter(number -> number.length() == 3).collect(Collectors.toSet());
		
		// without duplicates
		System.out.println("Set removes the duplicates : ");
		set.forEach(System.out::println);

		// using toList()
		List<String> list2 = numbers.stream().filter(number -> number.length() == 3).collect(Collectors.toList());
		
		// without duplicates
		System.out.println("List with duplicates: ");
		list2.forEach(System.out::println);
		
		// tomap() examples
		Map<String, Integer> wordsLength = words.stream().collect(Collectors.toMap(Function.identity(), String::length));
		
		System.out.println("toMap() output: ");
		wordsLength.forEach((key, value) -> System.out.println(key + " = "+value));
		
		Map<String, String> wordsCount = numbers.stream().collect(Collectors.toMap(Function.identity(), Function.identity(), (oldValue, newValue) -> oldValue+" repeated"));
		
		System.out.println("toMap() with duplicates: ");
		wordsCount.forEach((key, value) -> System.out.println(key + " = "+value));
		
		// toCollection() examples
		// to linkedlist
		List<String> linkedList = words.stream().collect(Collectors.toCollection(LinkedList::new));
		
		System.out.println("linkedList is instance of LinkedList = "+(linkedList instanceof LinkedList));
		
		// to linkedhashset
		Set<String> linkedhHashSet = words.stream().collect(Collectors.toCollection(LinkedHashSet::new));
		System.out.println("linkedhHashSet is instance of LinkedHashSet = "+(linkedhHashSet instanceof LinkedHashSet));
		
		// to linkedhashset
		Map<String, Integer> treeMap = words.stream().collect(Collectors.toMap(Function.identity(), String::length, (oldValue, newValue) -> newValue, TreeMap::new));
		System.out.println("treeMap is instance of TreeMap = "+(treeMap instanceof TreeMap));
	

	}

}

 

7. Conclusion


In this article, we've seen how to use the Collect() of java 8 Stream api with examples.

collect() method can be used to convert the stream into the List or Set or Map or LinkedList or TreeMap based on the need.

And also we can use collect() with the joining, groupingby(), partitionby(), counting().




Monday, December 6, 2021

Java 8 Comparator Lambda Examples

1. Overview


In this tutorial, We'll learn how to use the Comparator interface with lambda expression in Java 8 onwards.

Lambda expression is to replace the anonymous implementations and to reduce the boilerplate code.

This makes the code cleaner and focus more on the business logic rather than semantics.


Java community provided a few sets of rules and guidelines in creating the lambda statements.

Lambda syntax and invalid one are discussed in detail in the previous discussions "java 8 lambda expressions".

First, we will see the examples without lambda and then the next section will see the equivalent lambdas.

For sorting to work with lambda comparator, we have to use the Collections.sort() method.

Java Comparator Lambda Examples

Saturday, December 4, 2021

Java 8 Comparator thenComparing()

1. Overview

In this tutorial, We'll learn how to use Comparator.thenComparing() method in java 8 streams.

thenComparing() method is used to sort the list of objects by multiple fields. 


And also thenComparing() method is used to merge or join two comparators as a single one. The merged comparator is used to sort the collection by multiple fields.

Syntax:
default Comparator<T> thenComparing(Comparator<? super T> other)
This method returns a lexicographic-order comparator with another comparator. If this Comparator considers two elements equal, i.e. compare(a, b) == 0, other is used to determine the order.

Java 8 Comparator thenComparing() - Sort By Multiple Fields


Wednesday, December 1, 2021

Java 8 IllegalStateException “Stream has already been operated upon or closed” Exception (Stream reuse)

1. Overview

In this short tutorial, We'll see the most common exception "java.lang.IllegalStateException: stream has already been operated upon or closed". We may encounter this exception when working with the Stream interface in Java 8.

Can we collect stream twice after closing?
Java Stream reuse – traverse stream multiple times?




stream has already been operated upon or closed

Exception

java.lang.IllegalStateException: stream has already been operated upon or closed

Sunday, November 28, 2021

Java 8 Stream map() examples - Stream Conversions

1. Overview


In this article, we'll be learning about a new map() function in Java 8 that is introduced in Stream API. map() method converts a Stream from one form to another Stream. This takes input X type Stream and converts into Y type output Stream.

This is widely used as part of new JDK 8 api.

Java 8 Stream map() examples - Stream Conversions


Friday, November 26, 2021

Java 8 Streams - Join or Append Stream of Strings using Collectors.joining()

1. Overview

In this tutorial, We'll learn how to append or join a list of strings or stream of strings in java 8.

This joining is done with a specific delimiter or separator with the Collectors api method.

Use Collectors.joining() method joins the values of the stream with a delimiter specified. If the delimiter is not specified then it takes nothing as a separator. So, that final returned string will be having just all values concatenated from the stream.

Along with the joining, this method does the conversion from java 8 stream to string object with the default delimiter.

Java 8 Stream Join String


2. Collectors.joining() Method


Collectors.joining() method does concatenate the list of values or list of strings or stream of values or strings into a new string. 

For this method, we can pass the our own delimiter and and also we can supply the prefix, suffix to the output string.

joining() is an overloaded method and available in 3 versions.

public static Collector<CharSequence,?,String> joining()
public static Collector<CharSequence,?,String> joining(CharSequence delimiter)
public static Collector<CharSequence,?,String> joining(CharSequence delimiter,
                                                       CharSequence prefix,
                                                       CharSequence suffix)


joining(): Input elements are concatenated into a new String as encounter order in the stream.

joining(CharSequence delimiter): Input elements are concatenated into a new String with the given delimiter value as encounter order in the stream.

joining(CharSequence delimiter, CharSequence prefix, CharSequence suffix): Input elements are concatenated into a new String with the given delimiter, suffix and prefix values as encounter order in the stream.


3. Java 8 Stream Join String Examples


Next, let us write the example programs using all these 3 methods of Collectors.joining().

Below example program does the stream joining as string and converting stream to string.

package com.javaprogramto.java8.streams.join;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * Java Join Stream Of Strings and stream to string examples.
 * 
 * @author JavaProgramTo.com
 *
 */
public class StreamOfStringJoiningExample {

	public static void main(String[] args) {

		// Creating the List with string values using Arrays.asList() method
		List<String> stringsList = Arrays.asList("1", "2", "3", "4", "5");

		// java 8 join stream of strings or stream to string

		// Example - 1: with default delimiter
		String joinWithDefaultDelimiter = stringsList.stream().collect(Collectors.joining());

		// Example - 2: with delimiter
		String joinWithDelimiter = stringsList.stream().collect(Collectors.joining(":"));

		// Example - 3: with given delimiter, suffix and prefix
		String joinWithDelimiterSuffixPrefix = stringsList.stream().collect(Collectors.joining("|", "[", "]"));

		// printing the values
		System.out.println("Input List of strings : " + stringsList);
		System.out.println("joining() string : " + joinWithDefaultDelimiter);
		System.out.println("joining(delimiter) string : " + joinWithDelimiter);
		System.out.println("joining(delimiter, suffix, prefix) string : " + joinWithDelimiterSuffixPrefix);
	}
}

Output:
Input List of strings : [1, 2, 3, 4, 5]
joining() string : 12345
joining(delimiter) string : 1:2:3:4:5
joining(delimiter, suffix, prefix) string : [1|2|3|4|5]

From the output, we can observe the output from 3 methods with default delimiter, custom delimiter and with a prefix and suffix values.


4. Stream IllegalStateException: stream has already been operated upon or closed


In the above program, we have created the new stream every time we call collect() or joining() method. You may think, can we reuse the stream object for the next two calls. Thats mean first create the Stream object once using stream() method and use the same stream object for all joining() calls.

Look the below code and the output.

		// Creating the stream object once and reuse for every collect() call.
		Stream<String> stream = stringsList.stream();

		// java 8 join stream of strings or stream to string
		
		// Example - 1: with default delimiter
		String joinWithDefaultDelimiter = stream.collect(Collectors.joining());

		// Example - 2: with delimiter
		String joinWithDelimiter = stream.collect(Collectors.joining(":"));
		
		// Example - 3: with given delimiter pipe(|), suffix and prefix
		String joinWithDelimiterSuffixPrefix = stream.collect(Collectors.joining("|", "[", "]"));


Output:

Exception in thread "main" java.lang.IllegalStateException: stream has already been operated upon or closed
	at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:229)
	at java.base/java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:578)
	at com.javaprogramto.java8.streams.join.StreamOfStringJoiningExample.main(StreamOfStringJoiningExample.java:29)
We got the runtime exception because once the terminal method collect() is called stream will be closed. In the next step, we are trying to call collect() method on the closed stream.

We have already discussed in detail about the error "stream has already been operated upon or closed" and how can be handled using Supplier.


5. Conclusion


In this article, We've seen how to join the stream of strings and how to convert Stream to String in java 8 with help of the joining() method.




Ref 

Java 8 - Convert IntStream to String

1. Overview

In this tutorial, We'll learn how to convert IntStream into String value in java 8.

In previous tutorials, we have seen how to convert IntStream to List and IntStream to Array using stream API methods.

Java 8 - Convert IntStream to String

Java 8 - Convert IntStream to Array

1. Overview

In this tutorial, We'll learn how to convert IntStream to Array of ints in java 8.

IntStream is used to create infinite streams with the number series pattern.

But, some of the time we might need to convert the number series to an array.

Java 8 - Convert IntStream to Array

Java 8 - Convert IntStream To List and Other

1. Overview

In this tutorial, We'll learn how to convert IntStream to List in java 8 and java 16 above versions.

IntStream is used to create the infinite streams in java 8 and it has the method to convert it to array using toArray() method.

But there are no other methods to directly convert it to List or set.

Conversion of IntStream to List can be done in two ways.

Java 8 - Convert IntStream To List and Other

Java 8 Stream reduce

1. Overview

In this tutorial, We'll learn how to use reduce() method to produce the final result from the stream in java 8.

Stream API is added in java 8 and now reduce operation is heavily used by the developers.

reduce() method is a terminal operation of streams.

Java 8 Stream reduce


Thursday, November 25, 2021

Java 8 – Convert LocalDateTime to Timestamp & Vice Versa

1. Overview

In this tutorial, We'll learn how to convert LocalDateTime object into the Timestamp in java 8 new Date Time API.

If you are new to Java 8 or above, It is recommended to read java 8 new date-time API in java indepth 

And also we will learn how to convert LocalDate to TimeStamp in java 8.

Java 8 – Convert LocalDateTime to Timestamp & Vice Versa

Java 8 Integer Class new methods

1. Overview

In this tutorial, We'll learn what are the new methods added to the Integer class in Java 8.

Below are the new methods of integer class and look at each example to understand its usage.

All methods are static and access directly with class name. All unsigned methods work for positive and negetive integer values.

Java 8 Integer Class new methods


public static String toUnsignedString(int i, int radix)
public static String toUnsignedString(int i)
public static int parseUnsignedInt(String s, int radix) throws NumberFormatException
public static int parseUnsignedInt(String s) throws NumberFormatException
public static int hashCode(int value)
public static int compareUnsigned(int x, int y)
public static long toUnsignedLong(int x)
public static int divideUnsigned(int dividend, int divisor)
public static int remainderUnsigned(int dividend, int divisor)
public static int sum(int a, int b)
public static int max(int a, int b)
public static int min(int a, int b)

Wednesday, November 24, 2021

Java 8 Stream Collect to List

1. Overview

In this tutorial, We'll learn how to convert the stream of items into the list.

Below are the examples to collect the stream to list using Collectors.collect() and Collectors.toCollection() method.


Java 8 Stream Collect to List