Wednesday, September 11, 2019

Java 8 Optional ifPresent() - Working Example

1. Overview


In this tutorial, We'll learn how to perform an action if a value is present in Optional. Java 8 Optional ifPresent() does the job for us.

Instead of directly getting the value using get() method, first, it checks the condition value != null.

java-8-optional-ifpresent


The old way is done using the isPresent() method as below. But, ifPresent is much simplified than isPresent().

Java 8: How to Get the Last Element of a Stream in Java?

$type=blogging

1. Introduction

[post_ads]

in this tutorial, We will be looking at different ways to get the last element of a Stream in Java 8.

When we work with Stream then we have to go through one by one element of Stream. But, if we want to get directly last value and ignore the remaining preceding elements.

here are the possible ways to retrieve only the last value from the stream.

2. Using reduce() method

[lock]
reduce() method is part of the Stream API and we have to pass the lambda expression with two arguments. [/lock]

Syntax:


Optional reduce​(BinaryOperator accumulator)


Monday, August 26, 2019

StringBuffer VS StringBuilder in Java

1. Overview


In this tutorial, We'll be learning differences between the StringBuffer and StringBuilder in java. First, let us take a brief introduction to both and see the differences.

StringBuffer is introduced in java api first and then

2. StringBuffer


This is a thread-safe, mutable sequence of characters. A string buffer is just like a String, but it can be modified using its methods such as insert() or append() methods.

This class is a thread-safe and it can be shared among multiple threads.

Thursday, August 22, 2019

Java Examples to Create New Empty File and A Temporary File

1. Overview


In this tutorial, We'll be learning how to create a file in java and how to create a temp file in java.

Example programs demonstrated in the following methods.

createNewFile()
createTempFile()

Example Programs on Files

createNewFile() method is used to create a new empty file.
createTempFile() method is used to create a temporary file.

Java Examples To Work With Properties File (Read & Write)

1. Overview


In this tutorial, We'll be learning how to read from and write to the properties file in java.

Java API priovides a class Properties which is part of java.util package.

The Properties class stores the set of key, value pairs as properties. It internally stores all properties in a Stream. The Properties can be saved to a stream or loaded from a stream. Each key and its corresponding value in the property list stored as a string.

public class Properties
extends Hashtable<Object,​Object>

Properties inherit from Hashtable, the put and putAll methods can be applied to a Properties object. Their use is strongly discouraged as they allow the caller to insert entries whose keys or values are not Strings. The setProperty method should be used instead.

Java Program to Convert Degree Celsius to Kelvin & Kelvin to Celsius

1. Overview


In this tutorial, We'll learn how to convert Degree Celsius to kelvin in Java programming language. First, we will learn the formula and temperature conversion programs in java.

Degree celsius and kelvin are part of temparature mesures.

The formula for conversion:

K = ( °C + 273.15 )

Where K is kelvin and °C is degree celsius

Example 1:

Celsius: 100
Kelvin: 373.15

Example 2:

Celsius: 120
Kelvin: 393.15

Wednesday, August 21, 2019

Java - String to Int Conversion Examples

1. Overview


In this tutorial, We'll learn to convert String to integer in java.

We will be showing the example programs using the following methods and possible exceptions that occur at runtime.

Integer.parseInt()
Integer.valueOf()

For Example, We have a string "456" and want it to convert int type.

Tuesday, August 20, 2019

Java 8 Streams filter() - Working Examples

1. Overview


In this tutorial, We'll learn about the new Java 8 Streams API filter() method. This filter method is the one mostly used in streams. Streams build the operations sequentially and parallel.

filter() method takes Predicate which holds a condition. If the condition is true then this element is passed to the next operation in the stream.


We will discuss with example programs so that you can understand clearly.

First, will talk about syntax, examples and how it works internally.

Friday, August 16, 2019

Java 8 StreamSupport Examples

1. Overview


In this tutorial, We'll be learning Java 8 StreamSupport class methods with example programs. Let us see its syntax and how to convert iterable to Stream using StreamSupport.stream() method. This class is part of java.util.stream package.

Core methods of StreamSupport class are stream(), intStream(), doubleStream(), longStream().

Thursday, August 15, 2019

Java 8 MinguoDate API Examples

1. Overview


In this tutorial, We'll be learning MinguoDate introduced in Java 8. The MinguoDate class is immutable and thread-safe. So, it can be used in multithreaded applications without explicit synchronization.

This date operates using the Minguo calendar. This calendar system is primarily used in the Republic of China, often known as Taiwan. Dates are aligned such that 0001-01-01 (Minguo) is 1912-01-01 (ISO).

Below is the class MinguoDate internal declaration in API source code.

public final class MinguoDate
extends Object
implements ChronoLocalDate, Serializable


Now, We'll see the example programs to convert localdate to MinguoDate and from MinguoDate to local date.

Wednesday, August 14, 2019

Java 8 Files walk() Examples

1. Overview


In this tutorial, We'll be learning the Files API walk() method in java 8. walk() method is part of the Files class and java.nio.file package.

This method is used to walk through any given directory and retrieves Stream<Path> as the return value. This method traverses through all its subdirectories as well.

API Description:

Return a Stream that is lazily populated with Path by walking the file tree rooted at a given starting file. The file tree is traversed depth-first, the elements in the stream are Path objects that are obtained as if by resolving the relative path against start.

Note: This method must be used within a try-with-resources statement.

In this article, We'll see its syntax and example programs on how to list all the files in the directory, list directories and specific file patterns such as .csv or file name contains 'Match' word.

Java 8 - 13 Stream Terminal Operations With Examples

1. Overview


In this tutorial, We'll learn What are Terminal Operations in Java 8. List all Java 8 Stream Terminal Operations with Examples.

Java-8 Stream terminal operations produce a non-stream, results such as primitive value, a collection or no value at all. Terminal operations are typically preceded by intermediate operations that return another Stream which allows operations to be connected in a form of a query.

or

Terminal operations can be performed on Stream directly.
Whereas Stream Intermediate operations produce a stream as a result.


Tuesday, August 13, 2019

Java 8 IntPredicate Examples

1. Overview

In this tutorial, We'll be learning the new java 8 IntPredicate functional Interface with examples. This is part of java.util.function package.

In the last article, We've seen an in-depth article on Predicate Function Interface in Java 8. This works exactly similar to the Predicate. Predicate works for all data types but IntPredicate works only for int values.


Short Introduction:

IntPredicate represents a predicate (boolean-valued function) of one int-valued argument. This is the int-consuming primitive type specialization of Predicate. IntPredicate interface has a functional method test() which takes int as an argument and returns a boolean value. This interface has only one abstract method hence it is called FI.

We will be seeing the syntax and its example programs on test(int value), and(IntPredicate other), negate() and or(IntPredicate other) methods.

test() is an abstract method and the remaining 3 are default methods.

In-depth Functional Interfaces (FI) in Java 8 with examples

1. Overview


In this tutorial, We'll learn about Functional Interface added to Java 8. Functional Interface is abbreviated as FI.

These Functional Interfaces are used extensively in Lambda Expressions.

Please read article on "A Complete Guide to Lambda Expressions"

If you have a basic understanding of Lambda's that will help in using Functional Interface(FI) properly. But, We will discuss in short about Lambda's.


We will cover the following concepts in this article.

  • Intro to Lambda
  • Lambda Examples
  • Functional Interface Definition
  • @FunctionalInterface annotation
  • Built-in FI's
  • Types of Functional Interfaces with examples


Monday, August 12, 2019

Java 8 Predicate Working Examples

1. Overview


In this tutorial, We'll learn how to work and use the Predicate Functional Interface.

In the previous post, We have discussed "Introduction to Functional Interfaces in Java 8". Explained an easy manner to understand the type of Functional Interfaces.

Predicate Functional interface is part of java.lang.function package.

Predicate is one of the categories of Function Interfaces (Suppliers, Consumers, Predicates and Function)

Below is the definition from Predicate API.

@FunctionalInterface
public interface Predicate<T>

Predicate has a abstract method named test(T t) which takes only one argument and does return a boolean value such as true or false.

This is mainly used to test a condition to perform certain operations.

test(T t) method can be called as Functional Method. Below is the signature.
boolean test(T t)

Predicate has many non-abstract methods apart from test(). Those are two static and three default methods.

Java 8 IntStream anyMatch() Method Example

1. Overview


In this example tutorial, We'll be learning Java 8 IntStream API anyMatch() method to verify Predicate condition matches to any values in the IntStream.

In the last tutorial, We've seen how to check whether all elements are matched to predicate condition using allmatch() method.

Let us see anyMatch() syntax, Example programs on this method.

API Note:

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. If the stream is empty then false is returned and the predicate is not evaluated.

Java 8 IntStream allMatch() Method Example

1. Overview


In this article, We'll be learning a new java 8 API IntStream allMatch() method. This is very useful to match a condition to all of the IntStream values.

As we know, IntStream accepts only integer values (This is designed for only integer values to improve performance and avoid errors). Performance is enhanced by avoiding the type casting in case of String has only numbers.

API Note:

Returns whether all elements of this stream match the provided predicate. May not evaluate the predicate on all elements if not necessary for determining the result. If the stream is empty then true is returned and the predicate is not evaluated.

we have already seen a similar method allMatch() in Stream API.

Sunday, August 11, 2019

Java 8 IntStream boxed() Method Example

1. Overview

In this tutorial, We'll learn about the new java 8 IntStream API boxed() method.

IntStream boxed() returns a Stream consisting of the elements of this stream, each boxed to an Integer. That means to convert all primitive int values to wrapper Integer type objects Stream.

This is part of Java.util.IntStream API course.

Note: This method is part of Intermediate Operations. All these are invoked lazy and executed upon terminal operations invocation.

Terminal opeartions such as forEach(), forEachOrdered(), iterator() etc.

Saturday, August 10, 2019

Java 8 IntStream findFirst() Method Example

1. Overview

In this tutorial, We'll learn Java 8 IntStream API findFirst() method usage along with example programs. IntStream is part of java.util package.

We've already seen many methods of IntStream API.

This is used to get the first element from the stream. In this article, We will see its syntax, example program, and internal implementation.

API Note:

Returns an OptionalInt describing the first element of this stream, or an empty OptionalInt if the stream is empty. If the stream has no encounter order, then any element may be returned.

Friday, August 9, 2019

Java 8 – TemporalAdjusters examples

1. Overview


In this tutorial, We'll learn about the new Java 8 TemporalAdjusters class and its methods along with examples.

This is part of the new java 8 date and time API and in java.time.temporal package and class name TemporalAdjusters. This class now has predefined temporal objects to change the data as we want.

TemporalAdjusters class is a collection of TemporalAdjuster implementations.

First We will see the example programs on the TemporalAdjusters class and next take a look at the Temporal interface.

At last, We'll define custom TemporalAdjuster implementation.

Java ConcurrentSkipListSet Examples

1. Overview


In this tutorial, We'll guide to the new Java 1.6 version ConcurrentSkipListSet. This is part of the new Collection API and package java.util.concurrent.

This class is a direct subclass of AbstractSet and implements NavigableSet.

public class ConcurrentSkipListSet<E> extends AbstractSet<E> implements NavigableSet<E>, Cloneable, Serializable


ConcurrentSkipListSet is mainly used to keep the elements sorted according to their natural ordering. This is the default behavior and no need to provide the comparator logic to it. If we provide the Comparator at the time of constructor creation then it uses our logic to sort the set. ConcurrentSkipListSet internally built using ConcurrentSkipListMap. This is equivalent to TreeSet and works well in a concurrent environment.

Wednesday, August 7, 2019

Java 8 Optional flatMap() Method Example

1.Overview


In this tutorial, We'll learn how to wrap all nested Optional values into a Direct Map instead of having hierarchies.
You get a better understanding once you see the example.

You will be learning today syntax, examples and its internal implementation part.

This is part of our Optional Method series course.

API Description:

If a value is present, returns the result of applying the given Optional-bearing mapping function to the value, otherwise returns an empty Optional. This method is similar to map(Function), but the mapping function is one whose result is already an Optional, and if invoked, flatMap does not wrap it within an additional Optional.

Monday, August 5, 2019

Java WeakHashMap Working Examples

1. Overview


In this tutorial, We'll be talking about WeakHashMap in java and it is placed in java.util package.

WeakHashMap is implemented based on Hashtable with weak keys. Map internally is built on Entry objects. When adding a key-value pair, it will be stored in the Entry object. An entry in a WeakHashMap will automatically be removed when its key is no longer in ordinary use. So, once the key is deleted from the map it is eligible for Garbage Collection and we can not prevent from running GC on it. This class completely behaves differently than other Map implementations such as HashMap, LinkedHashMap, etc. And also it has efficiency parameters of initial capacity and load factor as same as HashMap.

java-weakhashmap

Sunday, August 4, 2019

Java 8 Optional equals() Method Example

1. Overview

In this tutorial, We'll learn how to compare the Optional value with another value or object. Optional is a java 8 new class and introduced in java.util package.

First, we'll understand the syntax and its meaning. Next, equals() example program and its internal implementation.

optional-equals


Optional class All Methods

API Note: 

Indicates whether some other object is "equal to" this Optional value. The other object is considered equal if it is also an Optional and; both instances have no value present or; the present values are "equal to" each other via equals().

Thumb rule is that the passed object also must be Optional object. Otherwise, this method will return false.

Saturday, August 3, 2019

Java 8 IntStream.Builder - Methods Examples

1. Introduction


In this tutorial, We'll learn how to use IntStream.Builder Interface in Java 8. This is part of java.util.stream package. We have already covered Java 8 Stream API.

IntStream.Builder follows the builder design pattern to build the IntStream object.

IntStream.Builder is a mutable builder for an IntStream. This creates an integer stream which can be added with the values or elements before invoking the build phase. We will discuss how to create a builder instance and its life cycle step by step in this article. For now, you need not worry about these terms. By the end of this article, you will be confident about this interface.



intstream-builder


In the end, We will write example programs using accept(), add() and build methods.

Friday, August 2, 2019

Java 8 DoubleSummaryStatistics API - Working Examples

1. Overview


In this tutorial, We'll guide to DoubleSummaryStatistics class which added in Java 8 API. This is introduced in java.util package.

DoubleSummaryStatistics

DoubleSummaryStatistics class is designed to get statistics of a for a stream such as count, min, max, sum, and average operations for double values or DoubleStream.

Thursday, August 1, 2019

Java 8 Optional filter() Method Example

1. Overview

In this tutorial, We'll discuss how to use Predicate with Optional class. The Java 8 optional class has a method filter() which takes Predicate as an argument.

Optional is a class and it is in java.util package. Optional is declared as final in its source code. Because no other classes can be inherited and to stop overriding the behavior.

Java 8 Optional filter


API Note: If a value is present, and the value matches the given predicate, returns an Optional describing the value, otherwise returns an empty Optional.

Wednesday, July 31, 2019

Java 8 Optional ofNullable() Method Example

1. Overview


In this tutorial, We'll learn ofNullable() example on how to create new Java 8 Optional object for any value or null value. Optional is part of java.util package.

Java 8 Optional ofNullable() Method Example


API Note: Returns an Optional describing the given value, if non-null, otherwise returns an empty Optional.

Tuesday, July 30, 2019

Java 8 Optional of() Method Example

1. Overview


In this tutorial, We'll learn how to create an Optional object for any value in Java 8. This is a very useful method to create an instance of Optional. Optional is a new class and introduced part of java.util package.

In last tutorial, We've discussed Optional.empty() method.

Let us take a look at Syntax, Example program on of() method.

API note: Returns an Optional describing the given non-null value. If null value, it throws NullPointerException.

Java 8 Optional of() Method Example


Monday, July 29, 2019

Java 8 Optional empty() Method Examples

1. Overview


In this tutorial, We'll learn how to create an empty Optional instance using Java 8 empty() method. Let us take at the Java 8 Optional empty() example program.
Before that let us take a look at the syntax first and then next its usage.

empty() method is used to create an empty Optional object. That means no value is present for this Optional. Optional is a final class.



optional-empty

Saturday, July 27, 2019

Java 8 IntStream empty() Method Example

1. Introduction


In this tutorial, We'll learn about Java 8 Instream API empty() method example programs.

empty() method is used to create a new empty Instream. The returned stream is a sequential stream. That means all the elements of Stream are processed one by one the order they appear in it.



Java8_IntStream_empty

Thursday, July 25, 2019

Java 8 Stream allMatch() Method

Stream allMatch() Method 


In this tutorial, We will see the example program on Java 8 Stream allMatch() method. allMatch() method checks whether all elements of Stream is matched to the given predicate then it returns true. Otherwise returns false.


This is called Terminal Operation because this is executed at the end of the stream. That means Stream is closed after the execution of allMatch() method.


Java 8 Stream allMatch()