Java String Format Examples

This article shows you how to format a string in Java, via String.format(). Here is the summary. Conversion Category Description %b, %B general true of false %h, %H general hash code value of the object %s, %S general string %c, %C character unicode character %d integral decimal integer %o integral octal integer, base 8 %x, …

Read more

Java mod examples

Both remainder and modulo are two similar operations; they act the same when the numbers are positive but much differently when the numbers are negative. In Java, we can use Math.floorMod() to describe a modulo (or modulus) operation and % operator for the remainder operation. See the result: | rem & +divisor| rem & -divisor …

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

How to add JAVA_HOME on Ubuntu?

On Ubuntu, we can add JAVA_HOME environment variable in /etc/environment file. Note /etc/environment system-wide environment variable settings, which means all users use it. It is not a script file, but rather consists of assignment expressions, one per line. We need admin or sudo to modify this it. Further Reading Ubuntu – EnvironmentVariables 1. JAVA_HOME 1.1 …

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

How to install Java JDK on macOS

This article shows how to install Java JDK on macOS, Homebrew package manager, manual installation, and switch between different JDK versions. Tested with macOS 11 Big Sur Homebrew 2.7.4 JDK 8, 14, 16, 16 (AdoptOpenJDK and OpenJDK) Topics Homebrew install latest Java (OpenJDK) on macOS Homebrew install Java 8 (OpenJDK) on macOS Homebrew install a …

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

How to stop and remove all docker containers?

In Docker, we cannot remove a running container, stop it first. Stop all running containers. Terminal $ sudo docker stop $(sudo docker ps -aq) Remove all stopped containers. Terminal $ sudo docker rm $(sudo docker ps -aq) 1. Stop Container 1.1 List all containers sudo docker ps Terminal $ sudo docker ps CONTAINER ID IMAGE …

Read more

Spring Boot redirect port 8080 to 8443

In Spring Boot 2.x, we can create a ServletWebServerFactory to redirect a port from HTTP 8080 to HTTPS 8443. Access localhost:8080, it will redirect to localhost:8443 1. ServletWebServerFactory For Spring Boot 2.x, try this: pom.xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> StartApplication.java package com.mkyong; import org.apache.catalina.Context; import org.apache.catalina.connector.Connector; import org.apache.tomcat.util.descriptor.web.SecurityCollection; import org.apache.tomcat.util.descriptor.web.SecurityConstraint; import …

Read more

Docker + Spring Boot examples

In this tutorial, we will show you how to Dockerize a Spring Boot web application (mvc + thymeleaf). Tested with Docker 19.03 Ubuntu 19 Java 8 or Java 11 Spring Boot 2.2.4.RELEASE Maven At the end of the article, we will create a Spring Boot MVC web application and run inside a docker container. P.S …

Read more

Java Map with Insertion Order

In Java, we can use LinkedHashMap to keep the insertion order. P.S HashMap does not guarantee insertion order. 1. HashMap Generate a HashMap, UUID as key, index 0, 1, 2, 3, 4… as value. JavaHashMap.java package com.mkyong.samples; import java.util.HashMap; import java.util.Map; import java.util.UUID; import java.util.stream.IntStream; public class JavaHashMap { public static void main(String[] args) { …

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 Trap – Autoboxing and Unboxing

The below program is a typical Java trap, and also a popular Java interview question. It has no compiler error or warning but running very slow. Can you spot the problem? JavaSum.java package com.mkyong; import java.time.Duration; import java.time.Instant; public class JavaSum { public static void main(String[] args) { Instant start = Instant.now(); Long total = …

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

How to change the JVM default locale?

In Java, we can use Locale.setDefault() to change the JVM default locale. JavaLocaleExample.java package com.mkyong.locale; import java.util.Locale; public class JavaLocaleExample { public static void main(String[] args) { // get jvm default locale Locale defaultLocale = Locale.getDefault(); System.out.println(defaultLocale); // set jvm locale to china Locale.setDefault(Locale.CHINA); // or like this //Locale.setDefault(new Locale("zh", "cn"); Locale chinaLocale = Locale.getDefault(); …

Read more

Java Scanner examples

Long live the Scanner class, a few examples for self-reference. 1. Read Input 1.1 Read input from the console. JavaScanner1.java package com.mkyong.io; import java.util.Scanner; public class JavaScanner1 { public static void main(String[] args) { try (Scanner scanner = new Scanner(System.in)) { System.out.print("Please enter your name: "); String input = scanner.nextLine(); System.out.println("name : " + input); …

Read more

Java – How to print a name 10 times?

This article shows you different ways to print a name ten times. 1. Looping 1.1 For loop JavaSample1.java package com.mkyong.samples; public class JavaSample1 { public static void main(String[] args) { for (int i = 0; i < 10; i++) { System.out.println("Java "); } } } Output Java Java Java Java Java Java Java Java Java …

Read more