How to add a List to another List in Java

Collection class in java.util provides addAll method which accepts a list and adds them to the source object. Since, List and ArrayList inherit from Collection, we can use this method to add a List to another List. boolean Collection.addAll(Collection) This method appends all the elements from the new collection to the end of the source … Read more

How to rename a file in Java

To rename a file, we can use File.renameTo() function from java.io package. However, renameTo() function requires a new File object with the new name that we want to name the source file, instead of just passing the new name to renameTo() function. So, to rename a file, we need to create two File objects, one … Read more

How to split a String in Java

In this post we will discuss on how to split a String using Java classes such as String, StringTokenizer and Scanner. String.split(delimiter) String.split(delimiter) splits the text at the given delimiter and creates an array of String objects. Output But when you want to split the text using pipe symbol (|), you need to escape that … Read more

How to convert byte array to String

In this post, we will discuss various methods to convert byte array to String. String(byte[]) This String constructor variant constructs a new String by decoding the bytes array using the default charset. String(byte[], Charset) This String constructor variant constructs a new String by decoding the bytes array using given Charset. Since, this constructor throws UnsupportedEncodingException, … Read more

How to Sort an ArrayList of Strings

To sort an ArrayList of Strings, we will use Collections class. Collections class in java.util consists of static methods written using polymorphic algorithms that process given collection and return a new collection. Below we discuss two variants of the sort method. Both sort methods require collection of objects that implement the Comparable interface providing the … Read more