Skip to main content

Posts

Showing posts from June, 2022

java.time.Period Class With Examples

The java.time.Period class is part of new date and time API added in Java 8 that represents a date-based amount of time in the ISO-8601 calendar system, such as '4 years, 2 months and 10 days'. Java Period class models a quantity or amount of time in terms of years, months and days. These three fields are always present, but may be set to zero. Period class doesn't consider daylight savings time when added to ZonedDateTime , it will add a conceptual day, trying to maintain the local time. For example, consider adding a period of one day to 18:00 on the evening before a daylight savings gap. The Period will add the conceptual day and result in a ZonedDateTime at 18:00 the following day. of() method in Period class You can get an instance of Period class using methods- of(int years, int months, int days) ofDays(int days) ofMonths(int months) ofWeeks(int weeks) ofYears(int years) public class PeriodExample { public static void main(String[] ar

Java Stream Collectors.collectingAndThen() Examples

In this tutorial you’ll see how to use Collectors.collectingAndThen() method with the help of some examples. Collectors.collectingAndThen() method in Java Stream As the name of the method itself suggests this method helps you to provide logic for two steps in a single method call. How to collect stream elements. What to do after collecting Stream elements. Syntax of collectingAndThen() method is as given below- Collector<T,A,RR> collectingAndThen(Collector<T,A,R> downstream, Function<R,RR> finisher) Here parameters are- downstream - A collector that is applied to stream elements. finisher - A function to be applied to the final result of the downstream collector Collectors.collectingAndThen() Java examples 1. If you are collecting stream elements to a List and want to convert that list to an unmodifiable list. import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; p

Convert Java Stream to Array - toArray() method

In this tutorial you’ll see how to convert a Stream to array using toArray() method of the Java Stream API. Java Stream toArray() method There are two overloaded toArray() methods- Object[] toArray() - Returns an array containing the elements of this stream. toArray(IntFunction<A[]> generator) - This method also returns an array containing the elements of this stream. In this method a generator function of type IntFunction is passed to allocate the returned array. The generator function takes an integer, which is the size of the desired array, and produces an array of the desired size. This method returns an array of the given type rather than the Object[] array so it is a more preferred method. Stream API toArray() Java examples 1. In the first example we’ll be converting a list of Strings into array of Strings using toArray method. public class StreamToArray { public static void main(String[] args) { List strList = Arrays.asList("A", "B&quo

Java Stream Collectors summingInt(), summingLong(), summingDouble()

In the tutorial Java Stream Collectors averagingInt(), averagingLong(), averagingDouble() we saw how Collectors class in Java Stream API provides methods like Collectors.averagingInt(), Collectors.averagingLong(), Collectors.averagingDouble() to get average of Stream on Integers, Long and Double respectively. Same way if you want to quickly add the stream elements there are Collectors.summing() methods which have the following forms for different types- summingInt(ToIntFunction<? super T> mapper) - To get sum of stream of integers. If no elements are present, the result is 0. summingLong(ToLongFunction<? super T> mapper) - To get sum of stream of longs. If no elements are present, the result is 0. summingDouble(ToDoubleFunction<? super T> mapper) - To get sum of stream of doubles. If no elements are present, the result is 0. Argument passed to the methods is of type ToIntFunction, ToLongFunction and ToDoubleFunction respectively. These are functio

Java Stream Collectors averagingInt(), averagingLong(), averagingDouble()

If you want average of Stream elements there are handy utility methods available in Collectors class to quickly do that, the methods are- Collectors.averagingInt()- To get average of stream of integers. Collectors.averagingLong()- To get average of stream of longs. Collectors.averagingDouble()- To get average of stream of doubles. Collectors.averaging methods in Java Syntax of these methods is as given below- Collector<T,?,Double> averagingInt(ToIntFunction<? super T> mapper) Collector<T,?,Double> averagingLong(ToLongFunction<? super T> mapper) Collector<T,?,Double> averagingDouble(ToDoubleFunction<? super T> mapper) All of these methods return a Collector that produces the arithmetic mean of the values. Argument passed is of type ToIntFunction, ToLongFunction and ToDoubleFunction respectively. These are functional interfaces with methods applyAsInt(T value) , applyAsLong(T value) , applyAsDouble(T value) that produces a i

Java Stream - Collectors Class And collect() Method

When using Java streams , most of the time you will have a Collection as a source for the stream but you can also do the opposite i.e. obtain a Collection from a Stream. To do that you can use collect() method in the Java Stream API. Here note that collect() method performs a mutable reduction operation on the elements of this stream which returns a mutable result container. This mutable result container can be a Collection class like ArrayList, HashSet or a StringBuilder etc. Table of contents collect() method in Java Stream Collectors class in Java Stream Java Collectors example Using collect method with Combiner collect() method in Java Stream collect() method is a terminal operation and there are two overloaded collect() methods. 1- <R,A> R collect(Collector<? super T,A,R> collector) - Performs a mutable reduction operation on the elements of this stream using a Collector. In the method type parameters are as- T- The type of input elements

Java Stream findFirst(), findAny() With Examples

In the Java Stream API there are two methods findFirst() and findAny() where- findFirst() returns the first element of the Stream. findAny() returns any element of the Stream. Table of contents Java Stream findFirst() method Java Stream findFirst() examples Java Stream findAny() method Java Stream findAny() examples Java Stream findFirst() method The findFirst() method returns an Optional describing the first element of this stream in case Stream is not empty, returns an empty Optional if the stream is empty. Optional<T> findFirst() findFirst() is a short-circuiting terminal operation which means it may terminate in finite time when presented with infinite input. Java Stream findFirst() examples 1. A simple example to get first element of the list where List is the source for the Stream. import java.util.Arrays; import java.util.List; import java.util.Optional; public class FindFirstDemo { public static void main(String[] args) { L

Java Primitive Type Streams With Examples

Java Stream API was one of the important addition in Java 8 and provides a very efficient way to process collection of objects. Since Stream only works with object references so using it with primitive types is not very efficient. You will need to use wrapper classes to wrap the primitive data types when used with Stream i.e. Stream<Integer>, Stream<Long>, Stream<Double> making it inefficient because of conversion of primitive types to corresponding objects. Fortunately Java Stream API provides primitive specializations of Stream for the primitive types int, long and double. The primitive type streams available in Java are- IntStream - This is the int primitive specialization of Stream. LongStream - long primitive specialization of Stream. DoubleStream - This is the double primitive specialization of Stream. Table of contents Creating primitive Streams empty() method of() method range() and rangeClosed() methods Using Ar

ArrayList Vs CopyOnWriteArrayList in Java

ArrayList is part of Java from version 1.2 where as CopyOnWriteArrayList was added in Java 5 as a thread-safe variant of ArrayList. In this post we’ll see the differences between ArrayList and CopyOnWriteArrayList in Java . CopyOnWriteArrayList Vs ArrayList in Java 1- Thread Safety: CopyOnWriteArrayList is thread safe. Thread safety in CopyOnWriteArrayList is achieved by making a fresh copy of the underlying array for all mutative operations (add, set, and so on). ArrayList in Java is not thread safe. 2- External synchronization: CopyOnWriteArrayList is already thread safe so no external synchronization needed. ArrayList can be synchronized externally by using Collections.synchronizedList() method which returns a synchronized List backed by the specified List. Read more about synchronizing ArrayList in this post- How to Synchronize ArrayList in Java 3- Iterator fail-fast or fail-safe: The iterator returned by CopyOnWriteArrayList is fail-safe and the iterator is

LinkedBlockingDeque in Java With Examples

LinkedBlockingDeque in Java is an implementation of BlockingDeque interface and is part of java.util.concurrent package. LinkedBlockingDeque, just like LinkedBlockingQueue , is an optionally-bounded blocking queue which means the capacity for the queue can be specified thus making it bounded or it can be left unspecified in which case capacity of the deque is Integer.MAX_VALUE. LinkedBlockingDeque in Java LinkedBlockingDeque is based on linked nodes where each node holds reference to both previous and next nodes. Linked nodes are dynamically created upon each insertion unless this would bring the deque above capacity. Since LinkedBlockingDeque is a deque (double ended queue) elements can be inserted and removed from both ends of the queue that is how LinkedBlockingDeque differs from the BlockingQueue implementations like ArrayBlockingQueue where elements are added to the end of the queue and retrieved from the head of the queue. LinkedBlockingDeque implementation is th

ConcurrentLinkedDeque in Java With Examples

ConcurrentLinkedDeque in Java is an unbounded concurrent deque which is thread-safe. It stores its elements as linked nodes where each node stores a reference to both previous and next nodes. ConcurrentLinkedDeque in Java implements Deque interface and is part of java.util.concurrent package. How ConcurrentLinkedDeque differs from the blocking Deque implementations like LinkedBlockingDeque is that ConcurrentLinkedDeque is non-blocking so the operations in this queue don’t block. Since ConcurrentLinkedDeque is non-blocking so the blocking methods like putFirst(), takeFirst() or putLast(), takeLast() which will block if required are not available. ConcurrentLinkedDeque is similar to its counterpart ConcurrentLinkedQueue , with one difference that it is a double ended queue. It means ConcurrentLinkedDeque allows insertion and removal from both ends. ConcurrentLinkedDeque has methods like addFirst() , addLast() , removeFirst() , removeLast() to facilitate insertion and remova

ConcurrentLinkedQueue in Java With Examples

ConcurrentLinkedQueue in Java is an unbounded queue which is thread-safe. It stores its elements as linked nodes where each node stores a reference to the next node. ConcurrentLinkedQueue class implements Queue interface and is part of java.util.concurrent package. How ConcurrentLinkedQueue differs from the BlockingQueue implementations like ArrayBlockingQueue , PriorityBlockingQueue is that ConcurrentLinkedQueue is non-blocking so the operations in this queue don’t block. Since ConcurrentLinkedQueue is non-blocking there are no put() or take() methods which will block if required. This queue orders elements FIFO (first-in-first-out). The head of the queue is that element that has been on the queue the longest time. The tail of the queue is that element that has been on the queue the shortest time. New elements are inserted at the tail of the queue, and the queue retrieval operations obtain elements at the head of the queue. ConcurrentLinkedQueue doesn’t allow null eleme

LinkedTransferQueue in Java With Examples

LinkedTransferQueue in Java is an implementation of the TransferQueue interface and is part of java.util.concurrent package. It was added in Java 7. TransferQueue interface in Java TransferQueue interface which extends BlockingQueue interface adds the capability where producers may wait for consumers to receive elements . In BlockingQueue implementations like ArrayBlockingQueue , PriorityBlockingQueue there are operations that wait if the queue is empty when retrieving an element, and wait for space to become available in the queue when storing an element. In the TransferQueue there are operations that block at the element level too . Java TransferQueue Methods Apart from the methods inherited from the BlockingQueue, TransferQueue adds the following methods to add the capability where the thread waits until the element is consumed by another thread. transfer(E e) - Transfers the element to a consumer, waiting if necessary to do so. tryTransfer(E e) - Transfers th

PriorityBlockingQueue in Java With Examples

PriorityBlockingQueue in Java is an implementation of BlockingQueue interface and is part of java.util.concurrent package. PriorityBlockingQueue is an unbounded queue PriorityBlockingQueue is logically unbounded, that's how it differs from ArrayBlockingQueue which is a bounded queue and LinkedBlockingQueue which is optionally-bounded. PriorityBlockingQueue though unbounded is created with an initial capacity which you can specify or defaults to 11 if not specified. This initial capacity governs the size of an array used to store the elements on the queue. Note that though the queue is logically unbounded, attempted additions may fail due to resource exhaustion (causing OutOfMemoryError). Java PriorityBlockingQueue Constructors PriorityBlockingQueue() - Creates a PriorityBlockingQueue with the default initial capacity (11) that orders its elements according to their natural ordering. PriorityBlockingQueue(int initialCapacity) - Creates a PriorityBlockingQue