Java 8 – Convert Instant to LocalDateTime

Java 8 examples to show you how to convert from Instant to LocalDateTime 1. Instant -> LocalDateTime The java.time.LocalDateTime has no concept of time zone, just provide a zero offset UTC+0. InstantExample1.java package com.mkyong.date; import java.time.Instant; import java.time.LocalDateTime; import java.time.ZoneOffset; public class InstantExample1 { public static void main(String[] argv) { // Parse a ISO 8601 …

Read more

Java – Display all ZoneId and its UTC offset

A Java 8 example to display all the ZoneId and its OffSet hours and minutes. P.S Tested with Java 8 and 12 1. Display ZoneId and Offset DisplayZoneAndOffSet.java package com.mkyong; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.ZoneOffset; import java.time.ZonedDateTime; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; public class DisplayZoneAndOffSet { public static final boolean SORT_BY_REGION = false; …

Read more

Java 8 – How to convert String to LocalDate

Here are a few Java examples of converting a String to the new Java 8 Date API – java.time.LocalDate DateTimeFormatter formatter = DateTimeFormatter.ofPattern("d/MM/yyyy"); String date = "16/08/2016"; //convert String to LocalDate LocalDate localDate = LocalDate.parse(date, formatter); The key is understand the DateTimeFormatter patterns Note You may interest at this classic java.util.Date example – How to …

Read more

Java 8 – How to sort a Map

Java 8 Stream examples to sort a Map, by keys or by values. 1. Quick Explanation Steps to sort a Map in Java 8. Convert a Map into a Stream Sort it Collect and return a new LinkedHashMap (keep the order) Map result = map.entrySet().stream() .sorted(Map.Entry.comparingByKey()) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> oldValue, LinkedHashMap::new)); P.S By …

Read more

Java 8 – Convert a Stream to List

A Java 8 example to show you how to convert a Stream to a List via Collectors.toList Java8Example1.java package com.mkyong.java8; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; public class Java8Example1 { public static void main(String[] args) { Stream<String> language = Stream.of("java", "python", "node"); //Convert a Stream to List List<String> result = language.collect(Collectors.toList()); result.forEach(System.out::println); } } output …

Read more

Java 8 – Filter a null value from a Stream

Review a Stream containing null values. Java8Examples.java package com.mkyong.java8; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; public class Java8Examples { public static void main(String[] args) { Stream<String> language = Stream.of("java", "python", "node", null, "ruby", null, "php"); List<String> result = language.collect(Collectors.toList()); result.forEach(System.out::println); } } output java python node null //

Java 8 – Convert Map to List

Few Java examples to convert a Map to a List Map<String, String> map = new HashMap<>(); // Convert all Map keys to a List List<String> result = new ArrayList(map.keySet()); // Convert all Map values to a List List<String> result2 = new ArrayList(map.values()); // Java 8, Convert all Map keys to a List List<String> result3 = …

Read more

How to backup and restore (import and export) MySQL database or table

This tutorial will show you how to back up and restore (import or export) MySQL / MariaDB database or tables. Table of contents: 1. MySQL – Backup or export databases and tables 2. MySQL – Restore or import databases and tables 3. Backup and Restore MySQL 4. References 1. MySQL – Backup or export databases …

Read more

JUnit + Spring integration example

In this tutorial, we will show you how to test the Spring DI components with JUnit frameworks. Technologies used : JUnit 4.12 Hamcrest 1.3 Spring 4.3.0.RELEASE Maven 1. Project Dependencies To integrate Spring with JUnit, you need spring-test.jar pom.xml <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> <exclusions> <exclusion> <groupId>org.hamcrest</groupId> <artifactId>hamcrest-core</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.hamcrest</groupId> <artifactId>hamcrest-library</artifactId> <version>1.3</version> …

Read more

JUnit – Categories Test

In JUnit, you can organize the test cases into different categories, and run those categorized test cases with @Categories.ExcludeCategory or @Categories.IncludeCategory Note This @Categories annotation is available since JUnit 4.12 1. Category = Marker Interface In JUnit, you need to create marker interfaces to represent the categories: PerformanceTests.java package com.mkyong.category; //category marker interface public interface …

Read more

JUnit – Assert if a property exists in a class

Includes hamcrest-library and test the class property and its value with hasProperty() : P.S Tested with JUnit 4.12 and hamcrest-library 1.3 ClassPropertyTest.java package com.mkyong; import org.junit.Test; import java.util.Arrays; import java.util.List; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.hasProperty; import static org.junit.Assert.assertThat; public class ClassPropertyTest { //Single Object @Test public void testClassProperty() { Book obj …

Read more

Java Custom Exception Examples

In Java, there are two types of exceptions – checked and unchecked exception. Here’s the summary : Checked – Extends java.lang.Exception, for recoverable condition, try-catch the exception explicitly, compile error. Unchecked – Extends java.lang.RuntimeException, for unrecoverable condition, like programming errors, no need try-catch, runtime error. 1. Custom Checked Exception Note Some popular checked exception : …

Read more

JUnit – Run test in a particular order

In JUnit, you can use @FixMethodOrder(MethodSorters.NAME_ASCENDING) to run the test methods by method name, in lexicographic order. P.S Tested with JUnit 4.12 ExecutionOrderTest.java package com.mkyong; import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runners.MethodSorters; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; //Sorts by method name @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class ExecutionOrderTest { @Test public void testB() { assertThat(1 + 1, is(2)); …

Read more

Intellij + Infinitest Continuous Testing

The Infinitest is a continuous testing plugin, it helps to run the test automatically. 1. Install on IntelliJ 1.1 In Plugins, clicks on the “Browse repositories…” 1.2 Type “Infinitest” and clicks on the “Install” button. 1.3 Restart the Intellij IDEA. 2. Add Infinitest facet In the project structure / settings, add a “Infinitest” facet. 3. …

Read more

Intellij IDEA – How to build project automatically

By default, Intellij IDEA doesn’t compile classes automatically. But, you can enable the auto compile feature by following steps : In “Project settings or preferences” Select “Build, Execution, Deployment -> Compiler” Checked Make project automatically P.S This feature is available since IDEA 12 References Brand New Compiler Mode in IntelliJ IDEA 12

JUnit – How to test a Map

Forget about JUnit assertEquals(), to test a Map, uses the more expressive IsMapContaining class from hamcrest-library.jar pom.xml <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> <exclusions> <exclusion> <groupId>org.hamcrest</groupId> <artifactId>hamcrest-core</artifactId> </exclusion> </exclusions> </dependency> <!– This will get hamcrest-core automatically –> <dependency> <groupId>org.hamcrest</groupId> <artifactId>hamcrest-library</artifactId> <version>1.3</version> <scope>test</scope> </dependency> </dependencies> 1. IsMapContaining Examples All the below assertThat checks will be passed. …

Read more

JUnit – How to test a List

First, exclude the JUnit bundled copy of hamcrest-core, and include the useful hamcrest-library, it contains many useful methods to test the List data type. pom.xml <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> <exclusions> <exclusion> <groupId>org.hamcrest</groupId> <artifactId>hamcrest-core</artifactId> </exclusion> </exclusions> </dependency> <!– This will get hamcrest-core automatically –> <dependency> <groupId>org.hamcrest</groupId> <artifactId>hamcrest-library</artifactId> <version>1.3</version> <scope>test</scope> </dependency> </dependencies> 1. Assert List …

Read more

Hamcrest – How to assertThat check null value?

Try to check null value with the Hamcrest assertThat assertion, but no idea how? @Test public void testApp() { //ambiguous method call? assertThat(null, is(null)); } 1. Solution 1.1 To check null value, try is(nullValue), remember static import org.hamcrest.CoreMatchers.* //hello static import, nullValue here import static org.hamcrest.CoreMatchers.*; import org.junit.Test; //… @Test public void testApp() { //true, …

Read more

Maven and JUnit example

In Maven, you can declare the JUnit dependency like this: pom.xml <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> </dependencies> But, it comes with a bundled copy of hamcrest-core library. $ mvn dependency:tree … [INFO] \- junit:junit:jar:4.12:test [INFO] \- org.hamcrest:hamcrest-core:jar:1.3:test … 1. Maven + JUnit + Hamcrest Note Not a good idea to use the default …

Read more

Gradle and JUnit example

In Gradle, you can declare the JUnit dependency like this: build.gradle apply plugin: ‘java’ dependencies { testCompile ‘junit:junit:4.12’ } By default, JUnit comes with a bundled copy of hamcrest-core $ gradle dependencies –configuration testCompile testCompile – Compile classpath for source set ‘test’. \— junit:junit:4.12 \— org.hamcrest:hamcrest-core:1.3 1. Gradle + JUnit + Hamcrest Normally, we need …

Read more

Logback – Set log file name programmatically

In Logback, it is easy to set a log file name programmatically : In logback.xml, declares a variable like ${log.name} In Java, set the variable via System.setProperty(“log.name”, “abc”) 1. Full example 1.1 A logback file, we will set the ${log.name} variable later. src/main/resources/logback.xml <?xml version="1.0" encoding="UTF-8"?> <configuration> <property name="PRO_HOME" value="/home/mkyong/ant/logs" /> <property name="USER_HOME" value="${PRO_HOME}" /> …

Read more

MongoDB – group, count and sort example

Some MongoDB examples to show you how to perform group by, count and sort query. 1. Test Data A whois_range collection, containing many records. > db.whois_range.find(); { "_id" : 1, "country" : "us", "source" : "ARIN", "status" : "NEW", "createdDate" : ISODate("2016-05-03T08:52:32.434Z") }, { "_id" : 2, "country" : "us", "source" : "ARIN", "status" : …

Read more

Java – find class fields with specified data type

Some Java reflection API examples. 1. Display all fields and data type A Java reflection example to loop over all the fields declared by a class. 1.1 A POJO. CompanyA.java package com.mkyong.test; import java.util.List; import java.util.Map; import java.util.Set; public class CompanyA { String orgName; int count; List<String> comments; Set<String> branches; Map<String, String> extra; //… } …

Read more

Java 8 flatMap example

This article explains the Java 8 Stream.flatMap and how to use it. Topic What is flatMap? Why flat a Stream? flatMap example – Find a set of books. flatMap example – Order and LineItems. flatMap example – Splits the line by spaces. flatMap and Primitive type 1. What is flatMap()? 1.1 Review the below structure. …

Read more

Java – How to convert Array to Stream

In Java 8, you can either use Arrays.stream or Stream.of to convert an Array into a Stream. 1. Object Arrays For object arrays, both Arrays.stream and Stream.of returns the same output. TestJava8.java package com.mkyong.java8; import java.util.Arrays; import java.util.stream.Stream; public class TestJava8 { public static void main(String[] args) { String[] array = {"a", "b", "c", "d", …

Read more

Java – Stream has already been operated upon or closed

In Java 8, Stream cannot be reused, once it is consumed or used, the stream will be closed. 1. Example – Stream is closed! Review the following example, it will throw an IllegalStateException, saying “stream is closed”. TestJava8.java package com.mkyong.java8; import java.util.Arrays; import java.util.stream.Stream; public class TestJava8 { public static void main(String[] args) { String[] …

Read more

Java 8 – Stream Collectors groupingBy examples

In this article, we will show you how to use Java 8 Stream Collectors to group by, count, sum and sort a List. 1. Group By, Count and Sort 1.1 Group by a List and display the total count of it. Java8Example1.java package com.mkyong.java8; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.function.Function; import java.util.stream.Collectors; public …

Read more

Windows 10 – Edit Hosts file

In this tutorial, we will show you how to add a mapping of IP addresses to host names in the Windows Hosts file. Windows Hosts file C:\Windows\System32\drivers\etc\hosts 1. Notepad – Run as Administrator In desktop, left-bottom search box, type notepad, right click on the notepad icon and select run as administrator. 2. Edit hosts 2.1 …

Read more

Java – How to override equals and hashCode

Some Java examples to show you how to override equals and hashCode. 1. POJO To compare two Java objects, we need to override both equals and hashCode (Good practice). User.java public class User { private String name; private int age; private String passport; //getters and setters, constructor } User user1 = new User("mkyong", 35, "111222333"); …

Read more

Java 8 – Convert List to Map

Few Java 8 examples to show you how to convert a List of objects into a Map, and how to handle the duplicated keys. Hosting.java package com.mkyong.java8 public class Hosting { private int Id; private String name; private long websites; public Hosting(int id, String name, long websites) { Id = id; this.name = name; this.websites …

Read more

Java Builder pattern examples

The Builder Pattern in Java is a creational design pattern that helps in constructing complex objects step by step. Here are three examples of the Builder pattern in Java: 1. Building a User Profile This example models a User with optional fields using the Builder Pattern. User.java package com.mkyong.builder; class User { private final String …

Read more

Java – Compare Enum value

In Java, you can use == operator to compare Enum value. 1. Java Enum example Language.java package com.mkyong.java public enum Language { JAVA, PYTHON, NODE, NET, RUBY } 2. Compare with == Example to compare enum value with == operator. Test.java package com.mkyong.java public class Test { public static void main(String[] args) { // Covert …

Read more

Logback – Disable logging in Unit Test

While the unit test is running in the IDE, the Logback is showing a lot of configuration or status like this : 21:16:59,569 |-INFO in ch.qos.logback.classic.LoggerContext[default] – Could NOT find resource [logback.groovy] 21:16:59,569 |-INFO in ch.qos.logback.classic.LoggerContext[default] – Could NOT find resource [logback-test.xml] 21:16:59,569 |-INFO in ch.qos.logback.classic.LoggerContext[default] – Found resource [logback.xml] at … //… omitted for …

Read more

Java 8 Streams filter examples

In this tutorial, we will show you few Java 8 examples to demonstrate the use of Streams filter(), collect(), findAny() and orElse() 1. Streams filter() and collect() 1.1 Before Java 8, filter a List like this : BeforeJava8.java package com.mkyong.java8; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class BeforeJava8 { public static void main(String[] args) …

Read more

Python – How to join two list

In Python, you can simply join two list with a plus + symbol like this: list1 = [1,2,3] list2 = [4,5,6] list3 = list1 + list2 print list3 #[1, 2, 3, 4, 5, 6] Note Try to compare with this Java example – how to join arrays. Python really makes join list extremely easy.

Java 8 – StringJoiner example

In this article, we will show you a few StringJoiner examples to join String. 1. StringJoiner 1.1 Join String by a delimiter StringJoiner sj = new StringJoiner(","); sj.add("aaa"); sj.add("bbb"); sj.add("ccc"); String result = sj.toString(); //aaa,bbb,ccc 1.2 Join String by a delimiter and starting with a supplied prefix and ending with a supplied suffix. StringJoiner sj …

Read more