How to convert String to Integer in Java

In Java, we can use Integer.valueOf(String) to convert a String to an Integer object; For unparsable String, it throws NumberFormatException. Integer.valueOf("1"); // ok Integer.valueOf("+1"); // ok, result = 1 Integer.valueOf("-1"); // ok, result = -1 Integer.valueOf("100"); // ok Integer.valueOf(" 1"); // NumberFormatException (contains space) Integer.valueOf("1 "); // NumberFormatException (contains space) Integer.valueOf("2147483648"); // NumberFormatException (Integer max …

Read more

Java – How to remove items from a List while iterating?

In Java, if we remove items from a List while iterating it, it will throw java.util.ConcurrentModificationException. This article shows a few ways to solve it. Table of contents 1. java.util.ConcurrentModificationException 2. Java 8 Collection#removeIf 2.1 removeIf examples 2.2 removeIf uses Iterator 3. ListIterator example 4. Filter and Collect example 5. References P.S Tested with Java …

Read more

Mocking Spring Data DateTimeProvider

In this article, we will demonstrate an integration test where we have to persist the entities with mocked auditing date fields when JPA Auditing is enabled. Technologies used: Spring Boot 2.4.0 Spring 5.3.1 JUnit Jupiter 5.7.0 Tomcat embed 9.0.39 Java 8 1. Project Dependencies pom.xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>com.h2database</groupId> …

Read more

Where is the java.security file?

In Java, we can find the java.security file at the following location: $JAVA_HOME/jre/lib/security/java.security $JAVA_HOME/conf/security For Java 8, and early version, we can find the java.security file at $JAVA_HOME/jre/lib/security/java.security. Terminal $ /usr/lib/jvm/java-8-openjdk-amd64/jre/lib/security$ ls -lsah total 12K 4.0K drwxr-xr-x 3 root root 4.0K Mei 12 11:53 . 4.0K drwxr-xr-x 8 root root 4.0K Mei 12 11:53 .. …

Read more

Java – How to convert a byte to a binary string

In Java, we can use Integer.toBinaryString(int) to convert a byte to a binary string representative. Review the Integer.toBinaryString(int) method signature, it takes an integer as argument and returns a String. Integer.java public final class Integer extends Number implements Comparable<Integer>, Constable, ConstantDesc { public static String toBinaryString(int i) { return toUnsignedString0(i, 1); } //… } If …

Read more

Java – Convert negative binary to Integer

Review the following Java example to convert a negative integer in binary string back to an integer type. String binary = Integer.toBinaryString(-1); // convert -1 to binary // 11111111 11111111 11111111 11111111 (two’s complement) int number = Integer.parseInt(binary, 2); // convert negative binary back to integer System.out.println(number); // output ?? The result is NumberFormatException! Exception …

Read more

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 – 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

Java – How to search a string in a List?

In Java, we can combine a normal loop and .contains(), .startsWith() or .matches() to search for a string in ArrayList. JavaExample1.java package com.mkyong.test; import java.util.ArrayList; import java.util.List; public class JavaExample1 { public static void main(String[] args) { List<String> list = new ArrayList<>(); list.add("Java"); list.add("Kotlin"); list.add("Clojure"); list.add("Groovy"); list.add("Scala"); List<String> result = new ArrayList<>(); for (String s …

Read more

Java – How to get keys and values from Map

In Java, we can get the keys and values via map.entrySet() Map<String, String> map = new HashMap<>(); // Get keys and values for (Map.Entry<String, String> entry : map.entrySet()) { String k = entry.getKey(); String v = entry.getValue(); System.out.println("Key: " + k + ", Value: " + v); } // Java 8 map.forEach((k, v) -> { …

Read more