Java 8 – How to convert Iterator to Stream

In Java 8, we can use StreamSupport.stream to convert an Iterator into a Stream. // Iterator -> Spliterators -> Stream Stream<String> stream = StreamSupport.stream( Spliterators.spliteratorUnknownSize( iterator, Spliterator.ORDERED) , false); Review the StreamSupport.stream method signature, it accepts a Spliterator. StreamSupport.java public static <T> Stream<T> stream(Spliterator<T> spliterator, boolean parallel) { Objects.requireNonNull(spliterator); return new ReferencePipeline.Head<>(spliterator, StreamOpFlag.fromCharacteristics(spliterator), parallel); } …

Read more

Java 8 – Find duplicate elements in a Stream

This article shows you three algorithms to find duplicate elements in a Stream. Set.add() Collectors.groupingBy Collections.frequency At the end of the article, we use the JMH benchmark to test which one is the fastest algorithm. 1. Filter & Set.add() The Set.add() returns false if the element was already in the set; let see the benchmark …

Read more

Java 8 – Get the last element of a Stream?

In Java 8, we can use reduce or skip to get the last element of a Stream. 1. Stream.reduce Java8Example1.java package com.mkyong; import java.util.Arrays; import java.util.List; public class Java8Example1 { public static void main(String[] args) { List<String> list = Arrays.asList("node", "java", "c++", "react", "javascript"); String result = list.stream().reduce((first, second) -> second).orElse("no last element"); System.out.println(result); } …

Read more

Is Comparator a function interface, but it has two abstract methods?

Review the Comparator class; it has two abstract methods, why it can be a function interface? Comparator.java package java.util; @FunctionalInterface public interface Comparator<T> { // abstract method int compare(T o1, T o2); // abstract method boolean equals(Object obj); // few default and static methods } Definition of function interface Conceptually, a functional interface has exactly …

Read more

Java 8 method references, double colon (::) operator

In Java 8, the double colon (::) operator is called method references. Refer to the following examples: Anonymous class to print a list. List<String> list = Arrays.asList("node", "java", "python", "ruby"); list.forEach(new Consumer<String>() { // anonymous class @Override public void accept(String str) { System.out.println(str); } }); Anonymous class -> Lambda expressions. List<String> list = Arrays.asList("node", "java", …

Read more

Java 8 Supplier Examples

In Java 8, Supplier is a functional interface; it takes no arguments and returns a result. Supplier.java @FunctionalInterface public interface Supplier<T> { T get(); } 1. Supplier 1.1 This example uses Supplier to return a current date-time. Java8Supplier1.java package com.mkyong; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.function.Supplier; public class Java8Supplier1 { private static final DateTimeFormatter dtf …

Read more

Java 8 UnaryOperator Examples

In Java 8, UnaryOperator is a functional interface and it extends Function. The UnaryOperator takes one argument, and returns a result of the same type of its arguments. UnaryOperator.java @FunctionalInterface public interface UnaryOperator<T> extends Function<T, T> { } The Function takes one argument of any type and returns a result of any type. Function.java @FunctionalInterface …

Read more

Java 8 BinaryOperator Examples

In Java 8, BinaryOperator is a functional interface and it extends BiFunction. The BinaryOperator takes two arguments of the same type and returns a result of the same type of its arguments. BinaryOperator.java @FunctionalInterface public interface BinaryOperator<T> extends BiFunction<T,T,T> { } The BiFunction takes two arguments of any type, and returns a result of any …

Read more

Java 8 – How to convert IntStream to int or int[]

Few Java 8 examples to get a primitive int from an IntStream. 1. IntStream -> int Java8Example1.java package com.mkyong; import java.util.Arrays; import java.util.OptionalInt; import java.util.stream.IntStream; public class Java8Example1 { public static void main(String[] args) { int[] num = {1, 2, 3, 4, 5}; //1. int[] -> IntStream IntStream stream = Arrays.stream(num); // 2. OptionalInt OptionalInt …

Read more

Java – Check if the date is older than 30 days or 6 months

This article shows Java 8 and legacy date-time APIs example to check if a date is 30 days or 6 months older than the current date. 1. Java 8 isBefore() 2. Java 8 ChronoUnit.{UNIT}.between() 3. Java 8 Period.between() 4. Legacy Calendar and Date 5. References 1. Java 8 isBefore() First minus the current date and …

Read more

Java 8 – How to Sum BigDecimal using Stream?

In Java 8, we can use the Stream.reduce() to sum a list of BigDecimal. 1. Stream.reduce() Java example to sum a list of BigDecimal values, using a normal for loop and a stream.reduce(). JavaBigDecimal.java package com.mkyong; import java.math.BigDecimal; import java.util.LinkedList; import java.util.List; public class JavaBigDecimal { public static void main(String[] args) { List<BigDecimal> invoices = …

Read more

Java 8 – Convert Optional<String> to String

In Java 8, we can use .map(Object::toString) to convert an Optional<String> to a String. String result = list.stream() .filter(x -> x.length() == 1) .findFirst() // returns Optional .map(Object::toString) .orElse(""); Samples A standard Optional way to get a value. Java8Example1.java package com.mkyong; import java.util.Arrays; import java.util.List; import java.util.Optional; public class Java8Example1 { public static void main(String[] …

Read more

Java 8 forEach print with Index

A simple Java 8 tip to print the Array or List with index in the front. 1. Array with Index Generate the index with IntStream.range. JavaListWithIndex.java package com.mkyong.java8; import java.util.List; import java.util.stream.Collectors; import java.util.stream.IntStream; public class JavaArrayWithIndex { public static void main(String[] args) { String[] names = {"Java", "Node", "JavaScript", "Rust", "Go"}; List<String> collect = …

Read more

Java 8 BiConsumer Examples

In Java 8, BiConsumer is a functional interface; it takes two arguments and returns nothing. @FunctionalInterface public interface BiConsumer<T, U> { void accept(T t, U u); } Further Reading – Java 8 Consumer Examples 1. BiConsumer JavaBiConsumer1.java package com.mkyong.java8; import java.util.function.Consumer; public class JavaBiConsumer1 { public static void main(String[] args) { BiConsumer<Integer, Integer> addTwo = …

Read more

Java 8 Consumer Examples

In Java 8, Consumer is a functional interface; it takes an argument and returns nothing. @FunctionalInterface public interface Consumer<T> { void accept(T t); } 1. Consumer Java8Consumer1.java package com.mkyong.java8; import java.util.function.Consumer; public class Java8Consumer1 { public static void main(String[] args) { Consumer<String> print = x -> System.out.println(x); print.accept("java"); // java } } Output java 2. …

Read more

Java 8 – How to calculate days between two dates?

In Java 8, we can use ChronoUnit.DAYS.between(from, to) to calculate days between two dates. 1. LocalDate JavaBetweenDays1.java package com.mkyong.java8; import java.time.LocalDate; import java.time.temporal.ChronoUnit; public class JavaBetweenDays1 { public static void main(String[] args) { LocalDate from = LocalDate.now(); LocalDate to = from.plusDays(10); long result = ChronoUnit.DAYS.between(from, to); System.out.println(result); // 10 } } Output 10 2. LocalDateTime …

Read more

Java 8 – Difference between two LocalDate or LocalDateTime

In Java 8, we can use Period, Duration or ChronoUnit to calculate the difference between two LocalDate or LocaldateTime. Period to calculate the difference between two LocalDate. Duration to calculate the difference between two LocalDateTime. ChronoUnit for everything. 1. Period JavaLocalDate.java package com.mkyong.java8; import java.time.LocalDate; import java.time.Period; public class JavaLocalDate { public static void main(String[] …

Read more

Java 8 BiPredicate Examples

In Java 8, BiPredicate is a functional interface, which accepts two arguments and returns a boolean, basically this BiPredicate is same with the Predicate, instead, it takes 2 arguments for the test. @FunctionalInterface public interface BiPredicate<T, U> { boolean test(T t, U u); } Further Reading Java 8 Predicate Examples 1. BiPredicate Hello World. If …

Read more

Java 8 – Convert Epoch time milliseconds to LocalDate or LocalDateTime

In Java 8, we can use Instant.ofEpochMilli().atZone() to convert the epoch time in milliseconds back to LocalDate or LocalDateTime Epoch time to LocalDate LocalDate ld = Instant.ofEpochMilli(epoch).atZone(ZoneId.systemDefault()).toLocalDate(); Epoch time to LocalDateTime LocalDateTime ldt = Instant.ofEpochMilli(epoch).atZone(ZoneId.systemDefault()).toLocalDateTime(); P.S Epoch time is the number of seconds that have elapsed since 0:00:00 UTC on 1 January 1970 1. Epoch …

Read more

Java 8 Predicate Examples

In Java 8, Predicate is a functional interface, which accepts an argument and returns a boolean. Usually, it used to apply in a filter for a collection of objects. @FunctionalInterface public interface Predicate<T> { boolean test(T t); } Further Reading Java 8 BiPredicate Examples 1. Predicate in filter() filter() accepts predicate as argument. Java8Predicate.java package …

Read more

Java 8 Stream findFirst() and findAny()

In Java 8 Stream, the findFirst() returns the first element from a Stream, while findAny() returns any element from a Stream. 1. findFirst() 1.1 Find the first element from a Stream of Integers. Java8FindFirstExample1.java package com.mkyong.java8; import java.util.Arrays; import java.util.List; import java.util.Optional; public class Java8FindFirstExample1 { public static void main(String[] args) { List<Integer> list = …

Read more

Java 8 – Convert LocalDate and LocalDateTime to Date

A Java example to convert Java 8 java.time.LocalDate and java.time.LocalDateTime back to the classic java.uti.Date. JavaDateExample.java package com.mkyong.time; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.ZonedDateTime; import java.util.Date; public class JavaDateExample { public static void main(String[] args) { // LocalDate -> Date LocalDate localDate = LocalDate.of(2020, 2, 20); Date date = Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant()); // LocalDateTime -> …

Read more

Java 8 – How to parse date with "dd MMM" (02 Jan), without year?

This example shows you how to parse a date (02 Jan) without a year specified. JavaDateExample.java package com.mkyong.time; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.util.Locale; public class JavaDateExample { public static void main(String[] args) { DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd MMM", Locale.US); String date = "02 Jan"; LocalDate localDate = LocalDate.parse(date, formatter); System.out.println(localDate); System.out.println(formatter.format(localDate)); } } Output …

Read more

Java 8 – Unable to obtain LocalDateTime from TemporalAccessor

An example of converting a String to LocalDateTime, but it prompts the following errors: Java8Example.java package com.mkyong.demo; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.Locale; public class Java8Example { public static void main(String[] args) { String str = "31-Aug-2020"; DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd-MMM-yyyy", Locale.US); LocalDateTime localDateTime = LocalDateTime.parse(str, dtf); System.out.println(localDateTime); } } Output Exception in thread "main" …

Read more

Java 8 – How to parse date with LocalDateTime

Here are a few Java 8 examples to parse date with LocalDateTime. First, find the DateTimeFormatter pattern that matches the date format, for example: String str = "2020-01-30 12:30:41"; DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); second, parse it with LocalDateTime.parse DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); String str = "2020-01-30 12:30:41"; LocalDateTime localDateTime = LocalDateTime.parse(str, dtf); 1. …

Read more

Java 8 Parallel Streams Examples

Few Java 8 examples to execute streams in parallel. 1. BaseStream.parallel() A simple parallel example to print 1 to 10. ParallelExample1.java package com.mkyong.java8; import java.util.stream.IntStream; public class ParallelExample1 { public static void main(String[] args) { System.out.println("Normal…"); IntStream range = IntStream.rangeClosed(1, 10); range.forEach(System.out::println); System.out.println("Parallel…"); IntStream range2 = IntStream.rangeClosed(1, 10); range2.parallel().forEach(System.out::println); } } Output Normal… 1 2 …

Read more

Java 8 – Convert ZonedDateTime to Timestamp

Java example to convert java.time.ZonedDateTime to java.sql.Timestamp and vice verse. 1. ZonedDateTime -> Timestamp TimeExample1.java package com.mkyong.jdbc; import java.sql.Timestamp; import java.time.ZonedDateTime; public class TimeExample1 { public static void main(String[] args) { ZonedDateTime now = ZonedDateTime.now(); // 1. ZonedDateTime to TimeStamp Timestamp timestamp = Timestamp.valueOf(now.toLocalDateTime()); // 2. ZonedDateTime to TimeStamp , no different Timestamp timestamp2 = …

Read more

Java 8 Stream – The peek() is not working with count()?

Many examples are using the .count() as the terminal operation for .peek(), for example: Java 8 List<String> l = Arrays.asList("A", "B", "C", "D"); long count = l.stream().peek(System.out::println).count(); System.out.println(count); // 4 Output – It’s working fine. A B C D 4 However, for Java 9 and above, the peek() may print nothing: Java 9 and above …

Read more

Java 8 – Convert LocalDateTime to Timestamp

In Java, we can use Timestamp.valueOf(LocalDateTime) to convert a LocalDateTime into a Timestamp. 1. LocalDateTime Timestamp Java example to convert java.time.LocalDateTime to java.sql.Timestamp and vice verse. TimeExample.java package com.mkyong; import java.sql.Timestamp; import java.time.LocalDateTime; public class TimeExample { public static void main(String[] args) { // LocalDateTime to Timestamp LocalDateTime now = LocalDateTime.now(); Timestamp timestamp = Timestamp.valueOf(now); …

Read more

Java 8 – Convert a Stream to Array

In Java 8, we can use .toArray() to convert a Stream into an Array. 1. Stream -> String[] StreamString.java package com.mkyong; import java.util.Arrays; public class StreamString { public static void main(String[] args) { String lines = "I Love Java 8 Stream!"; // split by space, uppercase, and convert to Array String[] result = Arrays.stream(lines.split("\\s+")) .map(String::toUpperCase) …

Read more

Java 8 – How to convert IntStream to Integer[]

The key is boxed() the IntStream into a Stream<Integer>, then only convert to an Array. StreamExample.java package com.mkyong; import java.util.Arrays; import java.util.stream.IntStream; import java.util.stream.Stream; public class StreamExample { public static void main(String[] args) { //int[] -> IntStream -> Stream<Integer> -> Integer[] int[] num = {3, 4, 5}; //1. int[] -> IntStream IntStream stream = Arrays.stream(num); …

Read more

Java 8 – How to sort list with stream.sorted()

Few examples to show you how to sort a List with stream.sorted() 1. List 1.1 Sort a List with Comparator.naturalOrder() package com.mkyong.sorted; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class StreamApplication { public static void main(String[] args) { List<String> list = Arrays.asList("9", "A", "Z", "1", "B", "Y", "4", "a", "c"); /* List<String> sortedList = list.stream() …

Read more

Java 8 Stream.iterate examples

In Java 8, we can use Stream.iterate to create stream values on demand, so called infinite stream. 1. Stream.iterate 1.1 Stream of 0 – 9 //Stream.iterate(initial value, next value) Stream.iterate(0, n -> n + 1) .limit(10) .forEach(x -> System.out.println(x)); Output 0 1 2 3 4 5 6 7 8 9 1.2 Stream of odd numbers …

Read more

Java – How to sum all the stream integers

The sum() method is available in the primitive int-value stream like IntStream, not Stream<Integer>. We can use mapToInt() to convert a stream integers into a IntStream. int sum = integers.stream().mapToInt(Integer::intValue).sum(); int sum = integers.stream().mapToInt(x -> x).sum(); Full example. Java8Stream.java package com.mkyong.concurrency; import java.util.Arrays; import java.util.List; import java.util.stream.Stream; public class Java8Stream { public static void main(String[] …

Read more

Java 8 Streams map() examples

In Java 8, stream().map() lets you convert an object to something else. Review the following examples : 1. A List of Strings to Uppercase 1.1 Simple Java example to convert a list of Strings to upper case. TestJava8.java package com.mkyong.java8; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class TestJava8 { public static void …

Read more

Java 8 Optional In Depth

Java 8 has introduced a new class Optional in java.util package. It is used to represent a value is present or absent. The main advantage of this new construct is that No more too many null checks and NullPointerException. It avoids any runtime NullPointerExceptions and supports us in developing clean and neat Java APIs or …

Read more

Java 8 – Math Exact examples

Java 8 introduced new methods in the Math class that will throw an ArithmeticException to handle overflows. These methods consist of addExact, substractExact, multiplyExact, incrementExact, decrementExact and negateExact with int and long arguments. In addition, there’s a static toIntExact method to convert a long value to an int that also throws ArithmeticException. Before Java 8 …

Read more