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

Java Swing – JFileChooser example

JFileChooser is a quick and easy way to prompt the user to choose a file or a file saving location. Below are some simple examples of how to use this class. JFileChooser has 6 constructors: JFileChooser() – empty constructor that points to user’s default directory JFileChooser(String) – uses the given path JFileChooser(File) – uses the …

Read more

How to read and write Java object to a file

Java object Serialization is an API provided by Java Library stack as a means to serialize Java objects. Serialization is a process to convert objects into a writable byte stream. Once converted into a byte-stream, these objects can be written to a file. The reverse process of this is called de-serialization. A Java object is …

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

Java – How to join Arrays

In this article, we will show you a few ways to join a Java Array. Apache Commons Lang – ArrayUtils Java API Java 8 Stream 1. Apache Commons Lang – ArrayUtils The simplest way is add the Apache Commons Lang library, and use ArrayUtils. addAll to join arrays. This method supports both primitive and object …

Read more

Debian – Show apt-get package version

On Debian, you can use apt-cache policy ‘package name’ to check the package version. 1.1 Display Tomcat7 version. $ sudo apt-cache policy tomcat7 tomcat7: Installed: (none) Candidate: 7.0.52-1ubuntu0.3 Version table: 7.0.52-1ubuntu0.3 0 500 http://archive.ubuntu.com/ubuntu/ trusty-updates/main amd64 Packages 500 http://security.ubuntu.com/ubuntu/ trusty-security/main amd64 Packages 7.0.52-1 0 500 http://archive.ubuntu.com/ubuntu/ trusty/main amd64 Packages 1.2 Display OpenJDK-7 version. $ sudo …

Read more

Java – Mutable and Immutable Objects

This article shows you the difference between Mutable and Immutable objects in Java 1. Mutable object – You can change the states and fields after the object is created. For examples: StringBuilder, java.util.Date and etc. 2. Immutable object – You cannot change anything after the object is created. For examples: String, boxed primitive objects like …

Read more

Gradle – How to continue build if test is failed

By default, the Gradle build process will be stopped and failed if any unit test is failed. $ gradle build :clean :compileJava :processResources :classes :compileTestJava :processTestResources UP-TO-DATE :testClasses :test com.mkyong.example.TestExample > test_example FAILED java.lang.Exception at TestExample.java:9 //… 3 tests completed, 1 failed :test FAILED //… BUILD FAILED // <————– see status In this article, we …

Read more

Gradle – How to display test result in the console

By default, gradle test displays only the test summary. Terminal % gradle test BUILD SUCCESSFUL in 4s 6 actionable tasks: 3 executed, 3 up-to-date P.S Gradle test generates the detailed tests’ result at the build/reports/tests/test/index.html page. P.S Tested with Gradle 6.7.1 1. Display test result in the console. 1.1 We add the testLogging events to …

Read more

How to print an Array in Java

In this article, we will show you a few ways to print a Java Array. Table of contents. 1. JDK 1.5 Arrays.toString 2. Java 8 Stream APIs 3. Java 8 Stream APIs – Collectors.joining 4. Jackson APIs 5. References 1. JDK 1.5 Arrays.toString We can use Arrays.toString to print a simple array and Arrays.deepToString for …

Read more

Gradle – Exclude commons-logging from Spring

Gradle example to exclude commons-logging from Spring frameworks. build.gradle compile(‘org.springframework:spring-webmvc:4.2.4.RELEASE’){ exclude group: ‘commons-logging’, module: ‘commons-logging’ } If you have multiple Spring dependencies, you have to exclude for each build.gradle compile(‘org.springframework:spring-webmvc:4.2.4.RELEASE’){ exclude group: ‘commons-logging’, module: ‘commons-logging’ } compile(‘org.springframework:spring-test:4.2.4.RELEASE’){ exclude group: ‘commons-logging’, module: ‘commons-logging’ } A better solution is excluding commons-logging at the project level. build.gradle configurations.all …

Read more

Jenkins – Could not find GradleWrapperMain

Create a Gradle project in Jenkins CI, source management with Git, and build with Gradle Wrapper 1. Problem Jenkins console output, the build is failed – “Could not find org.gradle.wrapper.GradleWrapperMain” [Gradle] – Launching build. [workspace] $ /var/lib/jenkins/jobs/GradleTest/workspace/gradlew clean test Error: Could not find or load main class org.gradle.wrapper.GradleWrapperMain Build step ‘Invoke Gradle script’ changed build …

Read more

How to use Gradle Wrapper

In this tutorial, we will show you how to create Gradle wrapper for your project and how to use it. What is Gradle wrapper? The Gradle wrapper allows you to run a Gradle task without requiring that Gradle is installed on your system. 1. Create a Gradle Wrapper 1.1 Declares a wrapper task. build.gradle task …

Read more

Gradle JaCoCo – Incompatible version 1006

A Gradle build + JaCoCo coverage report. build.gradle apply plugin: ‘java’ apply plugin: ‘eclipse-wtp’ apply plugin: ‘jacoco’ //code coverage repositories { mavenLocal() mavenCentral() } jacoco { toolVersion = "0.7.5+" } jacocoTestReport { reports { html.enabled = true xml.enabled = true csv.enabled = false } } P.S Tested with Gradle 2.10 1. Problem 1.1 Run the …

Read more

Java RMI Hello World example

RMI stands for Remote Method Invocation and it is the object-oriented equivalent of RPC (Remote Procedure Calls). RMI was designed to make the interaction between applications using the object-oriented model and run on different machines seem like that of stand-alone programs. The code below will give you the basis to Java RMI with a very …

Read more

Intellij IDEA – Auto reload a web application (hot deploy)

In this tutorial, we will show you how to ‘hot deploy’ or ‘hot swap’ a web application in IDEA. Note Tested with Intellij IDEA 14 and 15 1. Select exploded WAR Go Run –>> Edit Configurations –>> “Deployment” tab, clicks + icon –>> select an “exploded artifact” 2. Update classes and resources Select “Server” tab, …

Read more

Maven – Deploy web application to WildFly

In Maven, we can use the official JBoss WildFly Maven Plugin to deploy a web application (war file) to the WildFly application server. Technologies tested : Maven 3.3.9 WildFly 9.0.2.final WildFly Maven Plugin 1.1.0.Alpha5 P.S This Spring MVC web application will be used for this deployment test. 1. Deploy WAR To WildFly 1.1 Start WildFly …

Read more

Maven – webxml attribute is required

Maven package a web application and hits the following error message : $ mvn package //… [ERROR] Failed to execute goal org.apache.maven.plugins:maven-war-plugin:2.2:war (default-war) on project spring4-mvc-maven-ajax-example: Error assembling WAR: webxml attribute is required (or pre-existing WEB-INF/web.xml if executing in update mode) -> [Help 1] Solution 1. For servlet container < 3, make sure WEB-INF/web.xml file ...

Read more

Spring MVC + Mustache JS template example

In this tutorial, we will show you a Spring MVC + Mustache JS template web application example. Technologies used : Spring 4.2.4.RELEASE mustache.js JDK 1.8.0_66 Jackson 2.7 Eclipse 4.3 Tomcat 8 Maven 3 Bootstrap 3 Note This solution is still working, but recommend this simple Spring Boot + JMustache solution. In Spring, we can use …

Read more

Jetty – java.net.BindException: Address already in use

Start a Java webapp with Maven Jetty plugin. $ mvn jetty:run 1. Problem But it hits the following error messages : [WARNING] FAILED org.eclipse.jetty.maven.plugin.JettyServer@1f53481b: java.net.BindException: Address already in use at sun.nio.ch.Net.bind0(Native Method) at sun.nio.ch.Net.bind(Net.java:433) at sun.nio.ch.Net.bind(Net.java:425) at sun.nio.ch.ServerSocketChannelImpl.bind(ServerSocketChannelImpl.java:223) at sun.nio.ch.ServerSocketAdaptor.bind(ServerSocketAdaptor.java:74) at org.eclipse.jetty.server.ServerConnector.open(ServerConnector.java:321) at org.eclipse.jetty.server.AbstractNetworkConnector.doStart(AbstractNetworkConnector.java:80) //… 2. Solution By default, the maven-jetty-plugin start Jetty on port …

Read more

jQuery – Ajax request return 200 OK but error event is fired?

Review a jQuery Ajax form submit. $(document).ready(function () { $("#hostingForm").submit(function (e) { e.preventDefault(e); var data = {} data["id"] = $("#id").val(); data["domain"] = $("#domain").val(); data["name"] = $("#name").val(); //… $.ajax({ type: "POST", contentType: "application/json", url: "{{home}}/hosting/update", data: JSON.stringify(data), dataType: ‘json’, timeout: 600000, success: function (data) { console.log("SUCCESS: ", data); }, error: function (e) { console.log("ERROR: ", e); …

Read more

How to start Meteor on different port

By default, Meteor app start on port 3000 $ meteor [[[[[ ~/path-to/meteor/hello ]]]]] => Started proxy. => Started MongoDB. => Started your app. => App running at: http://localhost:3000/ 1. Meteor Port 9999 To start Meteor app on a different port, start Meteor with –port parameter. $ meteor –port 9999 [[[[[ ~/path-to/meteor/app ]]]]] => Started proxy. …

Read more

Spring @PathVariable – Why is value truncated after the last (.)dot?

Review the below @PathVariable example. @RequestMapping("/site") public class SiteController { @RequestMapping(value = "/{q}", method = RequestMethod.GET) public ModelAndView display(@PathVariable("q") String q) { return getModelAndView(q, "site"); } } See the following cases : For input /site/google, q = google For input /site/google.com, q = google where is the .com? For input /site/google.com.my, q = google.com For …

Read more