How to join two ArrayList in Java - Example

You can use the addAll() method from java.util.Collection interface to join two ArrayLists in Java. Since ArrayList implements List interface which actually extends the Collection interface, this method is available to all List implementation including ArrayList e.g. Vector, LinkedList. The Collection.addAll(Collection src) method takes a collection and adds all elements from it to the collection which calls this method e.g. target.addAll(source). After this call, the target will have all elements from both source and target ArrayList, which is like joining two ArrayList in Java. The second ArrayList will remain as it is but the first ArrayList on which you have added elements will have more elements. Its size will be equal to the sum of the size of first and second ArrayList.

How to reverse a singly linked list in Java? Example

In this article, I'll show you how to reverse a singly linked list in Java without recursion. A singly linked list, also known as just linked list is a collection of nodes which can only be traversed in one direction e.g. forward. Each node in the linked list contains two things, a data and a pointer to next node in the list. In order to reverse the linked list, we need to iterate through the list and at each step we need to reverse the link e.g. after first iteration head will point to null and next element will point to head. At the end of traversal when you reach the tail of linked list, the tail will point to the second last element and it will become a new head because you can traverse through all elements from this node.

How to read a text file into ArrayList in Java

Prior to Java 7, reading a text file into an ArrayList involves lot of boiler plate coding, as you need to read the file line by line and insert each line into an ArrayList, but from Java 7 onward, you can use the utility method Files.readAllLines() to read all lines of a text file into a List. This method return a List of String which contains all lines of files. Later you can convert this List to ArrayList, LinkedList, or whatever list you want to. Btw, this the fourth article in the series of reading a text file in Java. In the earlier parts, you have learned how to read a file using Scanner and BufferedReader(1). Then, reading the whole file as String (2) and finally reading a text file into array (3). This program is not very different from those in terms of fundamentals. We are still going to use read() method for Java 6 solution and will read all text until this method return -1 which signals the end of file.