Posts

Showing posts with the label Java Q&A

How to Convert Java 8 IntStream to a List

Image
1. Overview                     In this tutorial, we are going to convert an IntStream to List and to an array. IntStream is a stream of primitive int values and a List is an ordered collection that holds generic values. To convert a stream to the collection, we can call collect() method of Stream class, but this works when the streams hold non-primitive types. Calling collect() method on primitive streams give a compilation error "collect() in IntStream cannot be applied to". 2. Solutions 2.1. Call boxed() method before collecting to a List        IntStream has a method boxed() that returns a Stream consisting of the elements each boxed to an Integer. After getting a boxed stream, we can call the collect() method to convert into a List. Code: package streams; import java.util.List; import java.util.stream.Collectors; import java.util.stream.IntStream; public class IntStreamTest { public stati...

How Treeset checks for duplicates while inserting?

Treeset uses compareTo() or compare() methods to compare elements.  If the element you want to insert into treeset implements Comparable interface, then Treeset uses compareTo() method to compare with the elements already present in the set.  Treeset doesn't use equals() or hashcode() to compare elements. Some more points about TreeSet: The most fundamental behavior of TreeSet is it doesn't allow duplicate entries as it is also a set.  TreeSet preserves the order of elements in which they are inserted. TreeSet uses binary search to locate an item.  TreeSet is backed by TreeMap.  TreeSet implements NavigableSet If you have not provided Customer comparator and if the user defined element has not implemented Comparable interface, then adding an element throws Runtime error.  

Inner Classes & Nested Classes Java

As per java documentation An inner class is a non static class declared inside another class. A nested class is a static class declared inside another class, Even though it is declared inside another class, it won't be considered as an inner class. Some tricky points to remember: It is a compile-time error if an inner class declares a member that is explicitly or implicitly static, unless the member is a constant variable. A constant variable is a final variable of primitive type or type "String" that is initialized with a constant expression.  

How to write Immutable class in Java?

What is Immutability? 1. Immutability means read only, which means once you create Immutable object, you can't change it's state. How to make class Immutable? To make any class immutable, you have to apply following steps 1. Make the class as final, so that no other classes can extend. 2. Declare all the fields as private, so that no other classes can access directly. 3. Declare all the fields as final, and initialize those from constructor. 4. Provide getter methods for the private fields, But make sure to return copy of the field, not the actual field. if you return actual reference, it's state can be changeable. Advantages Of Immutable Objects: 1. One main advantage for using immutable objects is Thread Safety, because the values cannot ever change, they can be freely passed from thread to thread without ever needing locking. 2. This means that, because there is no locking with synchronized blocks, there is no bottleneck where multiple threads need to...

How to configure a JSP file in web.xml?

Image
In java web applications, you can directly access jsp files without any configuration. For example, http://localhost:8080/SimpleWebapp/Index.jsp, in this link we are requesting index.jsp directly without any config. But if you have placed your jsp files inside WEB-INF directory(see in the image - Welcome.jsp), you can't access directly. For this you need to configure the jsp in web.xml. Let's see how to do, 1. In web.xml, define both servlet & servlet-mapping tags. 2. Inside servlet( ) tag, add your jsp location inside the tag. "< jsp-file>/WEB-INF/Welcome.jsp< /jsp-file>" 3. Complete configuration is < servlet> < servlet-name> Welcome< /servlet-name> < jsp-file> /WEB-INF/Welcome.jsp< /jsp-file> < /servlet> < servlet-mapping> < servlet-name> Welcome< /servlet-name> < url-pattern> /Welcome< /url-pattern> < /servlet-mapping> The result is showed ...

Pattern Matching In Java

What is pattern matching? Pattern matching is nothing but searching for a specific pattern in a given text. Suppose you want to search for all occurrences of word "Trade" in the below text, you can use pattern matching. Example text: "Trade involves the transfer of goods. Possible synonyms of "trade" include "commerce" and "financial transaction". Types of trade include barter. A network that allows trade is called a market." In Java you can do pattern matching with the help of regular expressions. In this tutorial i am going to explain how to perform pattern matching with core classes and their methods. Let's take one more example. for example if you have a text that contains a some numbers and some characters (898498398TraderA), and you want to extract only digits(898498398) from that, you can use pattern matching with help of regular expressions. What Is Regular Expression? A Regular expression is just a string bu...

How to Convert Array to HashSet In Java

In this tutorial, i am going to explain how to convert given array to HashSet in java. Problem: Consider an array String[] strArr = {"abc","cde","def","efg","ghi"}; You need to convert it to HashSet. Solutions: 1. Iterate the given array and store the values in a HashSet : For iterating the array, use basic for loop or enhanced for loop. I am using enhanced for loop here. First create an empty HashSet and while iterating the for loop, insert the values into created HashSet object. Below is the code for this. package com.speakingcs.collections; import java.util.HashSet; public class ArrayToSet { public static void main(String[] args) { String[] strArr = {"abc","cde","def","efg","ghi","hij"}; // Set for storing values HashSet< String> strSet = new HashSet< String>(); ArrayToSet as = new ArrayToSet(); as.convertToSet(strArr,st...

How to unzip/extract files from Zip Archive in Java

Java has built in support for zipping files and unzipping the zip archives. In this tutorial i am going to extract/unzip files from a Zip archive. I am going to use ZipFile class for this purpose. It is under package java.util.zip The 3 classes, we will be using in this tutorial are 1. java.util.zip.ZipFile 2. java.util.zip.ZipEntry 3. java.util.zip.ZipException ZipFile is the class that represents the zipped file in Java. So if you want to parse zipped file, you need to create an object of ZipFile class by passing location of zipped file to it. Step 1: Creating ZipFile object. ZipFile zFile = new ZipFile("C:\Users\sreenath\Desktop\Test.zip"); here ZipFile object is pointing to the Text.zip file. Next is you need to get the contents of Text.zip file, you can get the contents by calling entries() method of ZipFile object, it returns all the entries of zip file as Enumeration object. Step 2: call entries() method on ZipFile object. Enumeration<? extends...

Different Ways to Traverse/Iterate/Loop a List In Java

Image
In this post, i will show 4 basic ways to traverse/iterate/loop a list in java. They are 1. Using basic for loop. 2. Using enhanced for loop. 3. Using an Iterator. 4. Using an while loop. consider you have a list of String objects. for example List<String> aList = Arrays.asList("abc","cde","def","efg","fgh","ghi","hij","ijk","jkl"); 1. Using Basic for Loop: As Lists such as ArrayList, LinkedList are ordered in nature, you can use basic for loop, to iterate these type of collections. The code is below. for(int i = 0, j = aList.size(); i < j; i++) { System.out.print(aList.get(i)+" "); } 2.Using Enhanced for Loop: The enhanced for loop, iterates List and Set type of collections only. The code in this approach is for(String item: aList) { System.out.print(item+" "); } 3.Using an Iterator with while Loop: Iterator aItr = aList.iterator(); ...

3 Ways to Get the Current Time In MilliSeconds In Java?

Image
You can get the current time in milli seconds in 3 ways in java. 1. By Using Date class: The Date class has a method named getTime(). It returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object. The code for this is Date d = new Date(); System.out.println(d.getTime()); 2.By Using Calendar class: The Calendar class has getTimeInMillis() for this purpose. It returns this Calendar's time value in milliseconds.Below is the code for this. Calendar c = Calendar.getInstance(); System.out.println(c.getTimeInMillis()); 3.By Using System class: The currentTimeMillis() method can be used to get the time in milli seconds. It is a static method in System class. It returns the difference, measured in milliseconds, between the current time and midnight, January 1, 1970 UTC. The code is System.out.println(System.currentTimeMillis()); Unlike Date and Calendar classes, which require an object to be created, in this ...

How to Remove Duplicate White Spaces in String Using Java?

Image
What is White space character in Java? White space is a character which represents space between the words. There are two types of white spaces, those are Horizontal white space, Vertical white space. Horizontal white spaces: These are the white spaces entered through spacebar, Tab keys of the keyboard. Vertical white spaces: These are the white spaces entered through ? Enter key of the keyboard, which results a new line character. Older keyboards such as typewrite keyboards have Return , key meaning "Carriage-Return" ,which is equivalent to new line character. So a white space character in a String can be a space , tab , new line , carriage return , form feed or vertical tab . replaceAll() : Use replaceAll() method of String class to remove white spaces. It's syntax is public String replaceAll(String regex, String replacement) It replaces the portion of the string that matched the given regular expression with the given replacement. To identify the ...

How to Reverse an Array in Java With and Without Using Additional Array?

Image
In this article, I will explain how to solve the given problem. We are going to solve this problem in two ways and also we will discuss which approach is efficient. Problem: Reverse the Given Array. Solution:         You can solve this problem in two ways. 1. Using an additional array which has same size as give array and type. 2. Without using the additional array. Let's see the first approach. 1. Using Additional Array :      Consider we have given an integer array with 10 elements i.e {1,2,3,4,5,6,7,8,9,10}. In this approach, we take an empty integer array which is of same size i.e 10, and we traverse the given array from tail to begin ( from last index to begin index) and insert the element in the additional array from begin to tail. Hence the 10th element from original array goes into 1st position of additional array, 9th element goes into 2nd position, 8th element goes to 3rd position and so on. Solutio...

4 Ways to check the given Integer is Even or Odd

    Checking the given integer is Even or Odd is a simple practice program for novice developers. The one way is, divide the given number with 2 and if the remainder is 0 - then it is even number, else it is odd number. Beginners use this algorithm to solve the problem, but there are some other ways, by which you can solve this problem. The 4 ways are Using Modulo Operator (%) . Using Division Operator ( / ). Using Bitwise AND Operator (&).  Using Left shift and Right shift operators (<<, >>).  Let's see the code in all ways. 1. Using Modulo Operator ( % ) :          This is the most used to method to check the given number is even or odd in practice. Modulo operator is used to get the remainder of a division. For example 5 % 2 returns 1 i.e the remainder when divided 5 by 2. So When ever, you divide a given number with 2 and if the remainder is 0 - then it is even number, else odd number. The c...

How to Convert an Array to ArrayList In Java ?

    Using Arrays.asList() method you can convert the given array to ArrayList in java. Let's see an example. The implementation of asList() method is like below in java.  public static <T> List<T> asList(T... a) {     return new ArrayList<T>(a);  } The Program is package com.speakingcs.collections; import java.util.Arrays; import java.util.List; public class ArrayToArrayList {     /**      * @param args      */     public static void main(String[] args) {                 String[] strArr = {"abc","bcd","cde","def","efg","fgh","ghi","hij","ijk"};         convertToArrayList(strArr);     }             public static void convertToArrayList(String[] strArr) {         List<...

How to Sort HashMap Based On Values in Java?

     HashMap is a data structure used to store "Key" and "Value" pairs. Unlike, Arrays, ArrayLists, and LinkedLists, It doesn't preserve order of elements in which they have inserted. So, sorting HashMap based on keys, or values is a tough interview question, if you don't know how to solve. Let's see how to solve the problem. 1. HashMap stores each key and value pair as an Entry<K,V> object. for example, given a hashmap, Map<String,Integer> aMap = new HashMap<String,Integer>(); for every insertion of key, value pair into the hash map, there exists one Entry<K,V> object. By making use of this Entry<K,V> object, we can sort the hashmap based on values. 2. Create a simple HashMap and insert some key and values. Map<String,Integer> aMap = new HashMap<String,Integer>();                 // adding keys and values         aMap....

How to get the substring of a given String In Java?

String are most common data types used in any programming languages. In Java String is an Object and is backed by a character array. For example, String str = "abc"; is equivalent to  char val[] = {'a','b','c'}; As String is an object, it has convenient methods to manipulate the contents of String. Remember, Strings are immutable in Java, which means, when ever you perform an action, which requires it's content change, a new String object will be created. Now, lets see which method, we can use to get sub string of the given String. substring() :      substring() method is used to obtain a portion of string between two different positions. The substring() method is overloaded in java, means it has two different method signatures. public String substring(int beginIndex) public String substring(int beginIndex, int endIndex) substring(int beginIndex) :      Use this method, when ever you want a portion of String, from the giv...

Difference Between == and equals() method in Java

First of all, the main difference between "==" and "equals()" is "==" is an operator where as equals() is a method . equals() method is already implemented in Object class. So every new class you write will automatically inherit the equals() method from Object class along with other methods. "==" With Primitives: Use == operator if you want to check for equality of primitive type variables, such as short, integer, long, boolean, float, double, byte. for example, int a = 5; int b = 5; System.out.println(a == b); returns true. Remember, you can't call equals() method on primitive data types, because they are not objects. So for primitives to check for equality, you always need to use '==' operator only.   "==" With Reference Variables: Don't use '==', for testing equality of two objects, for example, let's create two Integer objects, with same values. Integer a = new Integer(5); Int...

How to List the contents / sub files of a directory in Java?

Image
Even though, it looks a bit difficult, it's a simple interview question. If you observe the quesion carefully, the problem here is you need to print the contents of a dirctory to the console. In any operating system, a directory consists of files such as text files, zip files, images, videos, or can contain another directory inside it. To solve the problem, lets go through the solution, 1. First of all, consider a simple directory which consists of some files and one more directory inside it. for example "C:\Users\A8020\Desktop\Test". It consists of 5 pdf files and 1 sub directory. All you need to do is print the contents names to console. 2. In order to get the read access to the specified directory, you need to make use of File class. In object oriented languages such as Java, Scala, a class represents a real world object. Here the class "File" represents a file in the drive, and the file can be a directory, text file or any other. 3. So create an...

Java Program To Download A File From Website

           In this tutorial, we are going to write a program in java, that downloads a file from website.I am going to  download, a pdf file, the url for this is "http://eur-lex.europa.eu/legal-content/BG/TXT/PDF/?uri=OJ:JOL_2015_011_R_0004&from=EN". Following are the steps to follow. 1. First of all, you have to make an URL object for the above url, for this use URL class. You know, in Object oriented programming, every thing can be represented in classes and objects. Here URL is a class in Java that represents a website url.   URL url = new URL("http://eur-lex.europa.eu/legal-content/BG/TXT/PDF/?uri=OJ:JOL_2015_011_R_0004&from=EN"); Now this URL object, represents the above url in java programming notation. 2. The next thing to do is, you have to read from that url, for this purpose, for this purpose, call openStream() method, which returns a reference to the InputStream object. The code for this is InputS...

How To Find Current / System / Today's Date/Time/Both In Java 8

    Finding Today’s date in Java is sometimes necessary. For example, while creating excel reports, you may need to fill the current date in any column. The java.time package in java 8 has 3 classes for this purpose, those are  java.time.LocalDate  java.time.LocalTime  java.time.LocalDateTime All these 3 classes are final classes, you have to call one of their factory methods to get an instance. All the 3 classes have method now(), which gives an instance of the particular class. java.time.LocalDate : LocalDate is a  A date without a time-zone such as 2007-12-03. It’s an immutable object that represents date in the format “Year - Month - Day” . Getting Current Date In the format “YYYY-MM-DD” : In some cases, you only need current date without time information, in such cases use LocalDate class and call toString() method s on it’s object, i.e LocalDate.now().toString() . Here is the code. import java.time.LocalDate; import java.time...