Skip to main content

Posts

Showing posts from May, 2020

Read File Asynchronously in Java

This post shows how to read file in Java asynchronously using the java.nio.channels.AsynchronousFileChannel class. Using AsynchronousFileChannel you can create an asynchronous file channel for reading, writing, and manipulating a file. To see how to write a file asynchronously in Java, check this post- Write a File Asynchronously in Java Reading file using AsynchronousFileChannel For reading a file there are two read methods- One of the read() method returns a Future instance representing the result of an asynchronous computation. In another read() method CompletionHandler instance is passed as an argument which consumes the result of an asynchronous I/O operation. 1. Java program to read file asynchronously First let’s see a program which uses the read method that returns Future instance. Future<Integer> read(ByteBuffer bufffer, long position) - Reads a sequence of bytes from this channel into the given buffer, starting at the given file position. im

Java Immutable Map With Examples

In Java 9 new static factory method has been added to create an immutable Map in Java. In this article we’ll see an example of creating immutable Map using factory method and how it makes it more convenient than the previous option of using Collections.unmodifiableMap() . You can not remove or add elements from an immutable Map. Calling any mutator method on the Map will always cause UnsupportedOperationException to be thrown. Creating immutable or unmodifiable Map before Java 9 Before Java 9, Collections.unmodifiableMap() method was used to create an immutable Map. One thing to note with this method is that original Map can still be modified. import java.util.Collections; import java.util.HashMap; import java.util.Map; public class ImmutMap { public static void main(String[] args) { Map<String, String> numMap = new HashMap<String, String>(); numMap.put("1", "One"); numMap.put("2", "Two"); numMap.put("

Java Immutable Set With Examples

In Java 9 new static factory method has been added to create an immutable Set in Java. In this article we’ll see an example of creating immutable set using factory method and how it makes it more convenient than the previous option of using Collections.unmodifiableSet() . You can not remove or add elements from an immutable Set. Calling any mutator method on the Set will always cause UnsupportedOperationException to be thrown. Creating immutable or unmodifiable set before Java 9 Before Java 9, Collections.unmodifiableSet() method was used to create an immutable set. One thing to note with this method is that original set can still be modified. import java.util.Collections; import java.util.HashSet; import java.util.Set; public class ImmutSet { public static void main(String[] args) { Set<String> numSet = new HashSet<>(); numSet.add("1"); numSet.add("2"); numSet.add("3"); numSet.add("4"); Set<Stri

Java Immutable List With Examples

In Java 9 Immutable collections were added in Java that makes it easy to create an immutable List, Set or Map. In this article we’ll see how to use Immutable List in Java. Elements cannot be added, removed, or replaced once an immutable list is created. Calling any mutator method on the List will always cause UnsupportedOperationException to be thrown. Creating Immutable List before Java 9 Before Java 9 only way to create an immutable list was to use Collections.unmodifiableList(List<? extends T> list) method. Here is an example showing how to create unmodifiable list before Java 9. In the program you can see that original list can still be changed (a new element is added to it). On the other hand unmodifiable list instance can’t be mutated. import java.util.ArrayList; import java.util.Collections; import java.util.List; public class ImmutList { public static void main(String[] args) { List<String> numList = new ArrayList<>(); numList.add("1

Java Program to Find File Extension

While doing file I/O operations in Java you may need to know the extension of the file. In this post we’ll see a Java program to get the file extension. Since there is no direct Java File API method to get the file extension you will have to use the Java String class methods to do that. Another option is to use Apache IO where FilenameUtils has a method getExtension() to get the file name. But that requires Apache IO jar in the class path. Getting file extension Java program 1. In String class there is a lastIndexOf(int ch) method that gives the index of the last occurrence of the specified character, using that you can get the index of the last '.' and using subString() you can get the string after that last dot. That way you can get the extension of the passed file. public class FileExtension { public static void main(String[] args) throws IOException { File file = new File("F:\\knpcode\\links.txt"); String extension = getFileExtension(file);

Counters in Hadoop MapReduce

Counters in Hadoop MapReduce help in getting statistics about the MapReduce job. With counters in Hadoop you can get general information about the executed job like launched map and reduce tasks, map input records, use the information to diagnose if there is any problem with data, use information provided by counters to do some performance tuning, as example from counters you get information about spilled records and memory used, using that information you can try to fine tune your job. Table of contents Types of counters in Hadoop Built-in counters in Hadoop File System Counters Map-Reduce Framework Counters File Input Format Counters File Output Format Counters Job Counters User defined counters in Hadoop User defined counter example Types of counters in Hadoop With in Hadoop there are many built-in counters for the MapReduce job that are displayed on the console after running the job or you can use UI to analyze those counters. You c

Java String repeat() Method

If you want to repeat a String n number of times from Java 11 there is a repeat() method in String class to do that. public String repeat(int count) - Returns a string whose value is the concatenation of this string repeated count times. If this string is empty or count is zero then the empty string is returned. String repeat() method example public class App { public static void main( String[] args ){ String str = "Test"; System.out.println(str.repeat(4)); } } Output TestTestTestTest Option to repeat string till Java 10 Since repeat() method is added in Java 11 so before that using replace() method of the Java String class you could repeat the String. There are overloaded versions of replace method but you can use the following one. You can also use replaceAll() instead. replace(CharSequence target, CharSequence replacement) - Replaces each substring of this string that matches the literal target sequence with the specified literal replacement

Java Program to Reverse a String In-place

In this post we’ll see a Java program to reverse a String in-place. If we go by the definition of an in-place algorithm it doesn’t use any extra space, the space of the input data itself is used to modify the data and produce the output. Now we do know that String is immutable in Java so any modification to the original String results in creation of a new String object. That is in contrast to the in-place algorithm which requires that you shouldn’t use a new data structure to produce output. So, technically having an in-place algorithm for reversing a String in Java is not possible but stretching the technicality a bit we can argue that original string, if not used any more, gets garbage collected leaving us with single string object anyway. Keeping that argument in mind we can write a Java program to reverse a String in-place. There are two options for writing this program if you are permitted to use other classes then you can use StringBuilder class and its methods. If you a

Reverse an Array In-place Java Program

In this post we’ll see how to reverse an array in-place Java. Though it is easy to take another array and start storing elements from the last index to the first index of the original array to this new array in order to get reversed array but this approach means using auxiliary data structure, a new array to store the reversed elements making the space complexity of this approach O(n). Using an in-place algorithm means additional space is not used and the space provided by the input data structure itself is used to modify the elements to get the output. Thus the Java program to reverse an array in-place will not use any additional array and swap elements with in the original array to get the reversed array as output. Reverse array in-place Java program One thing to note here is that you don’t need to iterate the whole array, you need to iterate only n/2 array for the array of size n. Since the first and last elements, second and second last and so on are swapped in each iterat

What is In-place Algorithm

An in-place algorithm is an algorithm that doesn’t use any extra space to transform the input. It uses the same space used by input data and modify the data with in that space itself to produce the output. However a small amount of extra storage space is allowed for auxiliary variables. Sorting algorithms like Bubble sort , Selection Sort , Insertion Sort are in-place sorting algorithms. Merge sort is an example of not in-place or out-of-place sorting algorithm. Here is code snippet of bubble sort showing how the input array itself is used to produce output. With in the input array after comparing elements, swapping is done if required. Only extra space it uses is the temp variable. int[] arr = {61, 34, 10, 0, 15, 112, 53, 78, 39, 45}; int n = arr.length; for(int i = 0; i < n; i++){ for(int j = 0; j < (n - i - 1); j++){ if(arr[j] > arr[j+1]){ int temp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = temp; } } } Another simple example of

Stable and Unstable Sorting Algorithms

While reading about different sorting algorithms you would have come across the terms stable sorting algorithms and unstable sorting algorithms . In this post we’ll see what is the difference between stable and unstable sorting algorithms. Stable sorting algorithm A sorting algorithm is said to be stable if the order of the same values in the output remains the same as in input array. This is an example of stable sorting, element 12 appears twice at index 5 and at index 7. In the output array after sorting is done the order is maintained 12 which was at index 5 appears first and 12 which was at index 7 appears later. Unstable sorting algorithm In an unstable sorting algorithm the ordering of the same values is not necessarily preserved after sorting. Here you can see that the ordering for the same element 12 is not maintained after sorting. Stability with key, value pair Application of stability becomes more important when we have key value pairs where keys can be dup