Compile and Run Java in Command Line with External Jars

The following example shows how to compile and run Java program in command line mode with external jars. It is developed under Linux. 1. Compile & Run Java Program Without External Jar Let’s create a simple hello world program “helloworld.java”. public class helloworld{ public static void main(String[] args){ System.out.println("Hello!"); } }public class helloworld{ public static … Read more

LeetCode – Generate Parentheses (Java)

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. For example, given n = 3, a solution set is: “((()))”, “(()())”, “(())()”, “()(())”, “()()()” Java Solution 1 – DFS This solution is simple and clear. In the dfs() method, left stands for the remaining number of (, right stands … Read more

Convert Stream to Array in Java 8

To convert a Stream to an array, there is an overloaded version of toArray() method for Stream objects. The toArray(IntFunction<A[]> generator) method returns an array containing the elements of this stream, using the provided generator function to allocate the returned array. String[] stringArr = { "a", "b", "c", "d" }; Stream<String> stream = Stream.of(stringArr); String[] … Read more

Java Serialization

What is Serialization? In Java, object serialization means representing an object as a sequence of bytes. The bytes includes the object’s data and information. A serialized object can be written into a file/database, and read from the file/database and deserialized. The bytes that represent the object and its data can be used to recreate the … Read more

Enhanced For-loop vs. forEach() in Java 8

Assuming you have the following list: List<String> list = Arrays.asList("a", "b", "c", "d", "e", "f");List<String> list = Arrays.asList("a", "b", "c", "d", "e", "f"); if you want to do something by using each element in a collection, there are two ways: 1) list.forEach(s -> System.out.println(s));list.forEach(s -> System.out.println(s)); 2) for(String s: list){ System.out.println(s); }for(String s: list){ System.out.println(s); … Read more

Deep Understanding of ArrayList.iterator()

iterator often cause problems, because developers often do not know how it works. The following code is from source code of ArrayList. One common problem is throwing java.util.ConcurrentModificationException. This exception is actually throw in the remove method. remove() has to be called after next(). if remove() is called before next(), the size of arraylist changes, … Read more

Java Varargs Examples

1. What is Varargs in Java? Varargs (variable arguments) is a feature introduced in Java 1.5. It allows a method take an arbitrary number of values as arguments. public static void main(String[] args) { print("a"); print("a", "b"); print("a", "b", "c"); }   public static void print(String … s){ for(String a: s) System.out.println(a); }public static void … Read more

Java Runtime.exec() Linux Pipe

If you want to utilize Linux pipe advantages, you can do it in Java. You may want to do the following, which is wrong. String cmd = "ls" Process p = Runtime.getRuntime().exec(cmd);String cmd = "ls" Process p = Runtime.getRuntime().exec(cmd); The correct way of executing shell command is the following: String[] cmd = { "/bin/sh", "-c", … Read more

How to Calculate Time Difference in Java?

Given two strings of time, you may want to calculate the difference between them. The following provide a simple solution. import java.text.SimpleDateFormat; import java.util.Date;   public class Main { public static void main(String[] args) throws Exception{ String time1 = "12:00:00"; String time2 = "12:01:00";   SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss"); Date date1 = format.parse(time1); Date … Read more

How to write a counter in Java 8?

Writing a counter in Java can be as simple as 2 lines. In addition to its simplicity, we can also utilize the parallel computation to increase the counter’s performance. import java.util.stream.Collectors; import java.util.stream.Stream; import java.util.Map;   public class Java8Counter { public static void main(String[] args) { String[] arr = { "program", "creek", "program", "creek", "java", … Read more

Primitive Type Stream Examples

In addition to Stream, java.util.stream package also provide a set of primitive type Streams such as DoubleStream, IntStream and LongStream. The primitive type streams are pretty similar with Stream. In this post I will use the IntStream to illustrate how to use primitive type streams. Create an IntStream From integer array: IntStream stream = IntStream.of(2, … Read more

How to Use Optional Type in Java 8 ?

1. Correct Way to Use Optional Consider the following example: List<String> list = new ArrayList<String>(); list.add("java"); list.add("php"); list.add("python"); list.add("perl"); list.add("c"); list.add("lisp"); list.add("c#"); Stream<String> wordStream = list.stream();   Stream<Integer> lengthStream = wordStream.map(s -> s.length()); Optional<Integer> sum = lengthStream.reduce((x, y) -> x + y); System.out.println(sum.get());List<String> list = new ArrayList<String>(); list.add("java"); list.add("php"); list.add("python"); list.add("perl"); list.add("c"); list.add("lisp"); list.add("c#"); Stream<String> … Read more

Collect Stream Result Examples

Instead of reducing a stream to a value, we can also collect the results. We can collect results to an array, a set/list, or a map by using the Stream.collect() method. 1. Collect Stream Results to Array List<String> list = new ArrayList<String>(); list.add("java"); list.add("php"); list.add("python"); Stream<String> wordStream = list.stream();   Stream<Integer> lengthStream = wordStream.map(s -> … Read more

Reduce Stream Examples

The Java 8 Stream API contains a set of terminal operations (such as average, sum, min, max, and count) which return one value by combining the elements of a stream. Such terminal operations are called reduction operations. In addition to those terminal operations, the JDK also provides the general-purpose reduction method – reduce(), which this … Read more