How to compare two List of String in Java?

List: Collections Framework Java


The best approach to compare two List<String>

Source Code
import java.util.ArrayList;
import java.util.List;

/**
 * @author javaQuery
 */
public class CompareTwoListExample {

    public static void main(String[] args) {
        /* Create list of String */
        List<String> listString1 = new ArrayList<String>();
        /* Add element from 0th position */
        listString1.add("a");
        listString1.add("b");
        listString1.add("c");
        listString1.add("d");
        listString1.add("e");

        /* Print list */
        System.out.println("Initial List1:\n" + listString1);
        System.out.println("---------------------------------");

        /* Create list of String */
        List<String> listString2 = new ArrayList<String>();
        /* Add element from 0th position */
        listString2.add("e");
        listString2.add("d");
        listString2.add("c");
        listString2.add("a");
        listString2.add("b");
        
        /* Print list */
        System.out.println("Initial List2:\n" + listString2);
        System.out.println("---------------------------------");

        if(listString1 != null && listString2 != null && (listString1.size() == listString2.size())){
            listString1.removeAll(listString2);
            if(listString1.isEmpty()){
                System.out.println("Both list are same.");
            }else{
                System.out.println("Both list are not same");
            }
        }
    }
}

Output
Initial List1:
[a, b, c, d, e]
---------------------------------
Initial List2:
[e, d, c, a, b]
---------------------------------
Both list are same.

How to remove all elements from List except specific?

Collection Framework Java

retainAll(Collection<?> c)
Retains only the elements in this list that are contained in the specified collection. In other words, removes elements from list which is not available in specified list.

Source Code
import java.util.ArrayList;
import java.util.List;

/**
 * @author javaQuery
 */
public class RetainListExample {

    public static void main(String[] args) {
        /* Create list of String */
        List<String> listString = new ArrayList<String>();
        /* Add element from 0th position */
        listString.add("a");
        listString.add("b");
        listString.add("c");
        listString.add("d");
        listString.add("e");

        /* Print list */
        System.out.println("Initial List:\n" + listString);
        System.out.println("---------------------------------");

        /* Create another list of String */
        List<String> retainList = new ArrayList<String>();
        /* Add elements that you want to keep in final List */
        retainList.add("b");
        retainList.add("d");

        /* Call `retainAll(Collection<?> c)` and pass list of item you want to keep */
        listString.retainAll(retainList);

        /* Print list */
        System.out.println("List after retainAll(Collection<?> c):\n" + listString);
    }
}

Output
Initial List:
[a, b, c, d, e]
---------------------------------
List after retainAll(Collection<?> c):
[b, d]

How to convert List to Array in Java?

List to Array Collections Framework


Using List over regular Array is the best practice in Java. However in certain situations we have to convert List to Array. There are two versions of toArray() is available. Lets understand one after another.

When we need to convert Array to List?
  • Method is not overloaded to support collection. (i.e Available only MyMethod(String[] str) not MyMethod(List listStr))
  • Passing an Array to a method in other API or framework.

toArray()
This will return an Array of Object[].

T[] toArray(T[] a)
This will return an Array of given data type T[]. This is much more convenient to use. This conversion has different scenarios while converting to Array.

  1. Same size of Array: When you have Array of same size of List, It will convert normally.
  2. Less size of Array: When you have Array has less size of List, It'll increase the size of Array.
  3. Greater size of Array: When you have Array with greater size of List, The element in the array immediately following the end of the list is set to null. (JAVADOC: This is useful in determining the length of the list only if the caller knows that the list does not contain any null elements.)

Source code
import java.util.ArrayList;
import java.util.List;

/**
 * @author javaQuery
 */
public class ListToArrayExample {

    public static void main(String[] args) {
        /* Create list of String */
        List<String> listString = new ArrayList<String>();
        /* Add element from 0th position */
        listString.add("a");
        listString.add("b");
        listString.add("c");

        /* Get an Array of Object */
        Object[] obj = listString.toArray();
        /* Loop through all elements */
        for (Object object : obj) {
            /* Check object is instanceof String */
            if (object instanceof String) {
                System.out.println(object.toString());
            }
        }
        System.out.println("---------------------------------");
        System.out.println("An array of same size of List");
        /* Create an array of String */
        String[] arrayString = new String[listString.size()];
        /* Get Array of String */
        arrayString = listString.toArray(arrayString);
        /* Loop through all elements */
        for (String str : arrayString) {
            System.out.println(str);
        }
        
        System.out.println("---------------------------------");
        System.out.println("An array of less size than List(*T[] toArray(T[] a) will increase the size of Array)");
        /* Create an array of String */
        String[] arrayStringLessSize = new String[2];
        /* Get Array of String */
        arrayStringLessSize = listString.toArray(arrayStringLessSize);
        /* Loop through all elements */
        for (String str : arrayStringLessSize) {
            System.out.println(str);
        }
        
        System.out.println("---------------------------------");
        System.out.println("An array of greater size than List");
        System.out.println("(T[] toArray(T[] a): The element in the array immediately following the end of the list is set to null)");
        /* Create an array of String */
        String[] arrayStringGreaterSize = new String[5];
        arrayStringGreaterSize[3] = "x";
        arrayStringGreaterSize[4] = "y";
        System.out.println("** Array before T[] toArray(T[] a) **");
        /* Loop through all elements */
        for (String str : arrayStringGreaterSize) {
            System.out.println(str);
        }
        
        /* Get Array of String */
        arrayStringGreaterSize = listString.toArray(arrayStringGreaterSize);
        System.out.println("** Array after T[] toArray(T[] a) **");
        /* Loop through all elements */
        for (String str : arrayStringGreaterSize) {
            System.out.println(str);
        }
    }
}

Output
a
b
c
---------------------------------
An array of same size of List
a
b
c
---------------------------------
An array of less size than List(*T[] toArray(T[] a) will increase the size of Array)
a
b
c
---------------------------------
An array of greater size than List
(T[] toArray(T[] a): The element in the array immediately following the end of the list is set to null)
** Array before T[] toArray(T[] a) **
null
null
null
x
y
** Array after T[] toArray(T[] a) **
a
b
c
null
y

Your security settings have blocked an application signed with an expired or not-yet-valid certificate from running

We are using applet in our project and Its signed by code signing certificate. It was working fine before expiry date of code signing certificate. We renewed our code signing certificate and signed and executed applet again and but we got the following exception...
com.sun.deploy.security.BlockedException: Your security settings have blocked an application signed with an expired or not-yet-valid certificate from running
    at com.sun.deploy.security.SandboxSecurity.showBlockedDialog(Unknown Source)
    at com.sun.deploy.security.TrustDecider.askUser(Unknown Source)
    at com.sun.deploy.security.TrustDecider.validateChain(Unknown Source)
    at com.sun.deploy.security.TrustDecider.isAllPermissionGranted(Unknown Source)
    at sun.plugin2.applet.Plugin2ClassLoader.isTrustedByTrustDecider(Unknown Source)
    at sun.plugin2.applet.Plugin2ClassLoader.getTrustedCodeSources(Unknown Source)
    at com.sun.deploy.security.CPCallbackHandler$ParentCallback.strategy(Unknown Source)
    at com.sun.deploy.security.CPCallbackHandler$ParentCallback.openClassPathElement(Unknown Source)
    at com.sun.deploy.security.DeployURLClassPath$JarLoader.getJarFile(Unknown Source)
    at com.sun.deploy.security.DeployURLClassPath$JarLoader.access$1000(Unknown Source)
    at com.sun.deploy.security.DeployURLClassPath$JarLoader$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.deploy.security.DeployURLClassPath$JarLoader.ensureOpen(Unknown Source)
    at com.sun.deploy.security.DeployURLClassPath$JarLoader.(Unknown Source)
    at com.sun.deploy.security.DeployURLClassPath$3.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.deploy.security.DeployURLClassPath.getLoader(Unknown Source)
    at com.sun.deploy.security.DeployURLClassPath.getLoader(Unknown Source)
    at com.sun.deploy.security.DeployURLClassPath.getResource(Unknown Source)
    at sun.plugin2.applet.Plugin2ClassLoader$2.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at sun.plugin2.applet.Plugin2ClassLoader.findClassHelper(Unknown Source)
    at sun.plugin2.applet.Applet2ClassLoader.findClass(Unknown Source)
    at sun.plugin2.applet.Plugin2ClassLoader.loadClass0(Unknown Source)
    at sun.plugin2.applet.Plugin2ClassLoader.loadClass(Unknown Source)
    at sun.plugin2.applet.Plugin2ClassLoader.loadClass0(Unknown Source)
    at sun.plugin2.applet.Plugin2ClassLoader.loadClass(Unknown Source)
    at sun.plugin2.applet.Plugin2ClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.plugin2.applet.Plugin2ClassLoader.loadCode(Unknown Source)
    at sun.plugin2.applet.Plugin2Manager.initAppletAdapter(Unknown Source)
    at sun.plugin2.applet.Plugin2Manager$AppletExecutionRunnable.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)

Root Cause
After all possible solution from Internet like exception site list and few other I started looking for all tiny bit of applet and found that we are using bouncy castle jar in our applet. I decompiled jar using jd-gui and found that bouncy castle jar is also signed. So I pulled out certificate details of bouncy castle by using following command.
$>"C:\Program Files\Java\jdk1.6.0_25\bin\jarsigner.exe" -verify -verbose -certs bouncy-castle.jar
The developer integrate this jar in our applet left the job and used same code signing certificate for bouncy castle.

Solution
I signed my applet and bouncy castle jar with renewed code signing certificate and Its working like as always. It may possible this solution doesn't help you but this is for those who uses other jar in their applet and face the same issue.

Conclusion
You have to sign all jar that you are using in your applet.

How List.add() and List.addAll() works?

Java Collections

We will understand various cases for adding elements in List. I created graphics that will help you to understand the behind the scene.

List.add(E e)
This will add element in List from 0th position to nth position based on last index of List.



List.add(int index, E element)
This will add element in List at the specified index. If there exists any element at the specified position then It'll shift down all the elements from specified position and add new element at the given position.



List.addAll(Collection c)
This will add another list at the end of current list.



List.addAll(int index, Collection c)
This will add another List at the specified index. If there exists any element at the specified position then It'll shift down all the elements from specified position and add new elements from the given position.



Source Code
import java.util.ArrayList;
import java.util.List;

/**
 * @author javaQuery
 */
public class AddListExample {

    public static void main(String[] args) {
        /* Create list of String */
        List listString = new ArrayList();
        /* Add element from 0th position */
        listString.add("a");
        listString.add("c");
        listString.add("d");

        /* Print list */
        System.out.println("Initial List:\n" + listString);
        System.out.println("---------------------------------");

        /* Add element at 1st position */
        listString.add(1, "b");
        System.out.println("List after add(int index, E element):\n" + listString);
        System.out.println("---------------------------------");

        /* Create another list of String */
        List addAllListBeginning = new ArrayList();
        /* Add element in list */
        addAllListBeginning.add("e");
        addAllListBeginning.add("f");

        /* Add `addAllListBeginning` at the end of `listString` */
        listString.addAll(addAllListBeginning);

        /* Print list */
        System.out.println("List after addAll(Collection c):\n" + listString);
        System.out.println("---------------------------------");

        /* Create another list of String */
        List addAllListAtIndex = new ArrayList();
        /* Add element in list */
        addAllListAtIndex.add("x");
        addAllListAtIndex.add("y");
        addAllListAtIndex.add("z");

        /* Add `addAllListAtIndex` at the specified index */
        listString.addAll(2, addAllListAtIndex);
        System.out.println("List after addAll(int index, Collection c):\n" + listString);
    }
}

Output
Initial List:
[a, c, d]
---------------------------------
List after add(int index, E element):
[a, b, c, d]
---------------------------------
List after addAll(Collection c):
[a, b, c, d, e, f]
---------------------------------
List after addAll(int index, Collection c):
[a, b, x, y, z, c, d, e, f]

How to sort a List in Java?

Collections Framework Java


What is List?
List is an Interface provided by Collections framework. List used store sequence of elements. User has precise control over list like where in the list each element is inserted. Used can access list by their index(position).

Source Code
Below code gives you example on how you can sort a List.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author javaQuery
 */
public class SortingListExample {

    public static void main(String[] args) {
        /* Create list of Integer */
        List listInteger = new ArrayList();
        /* Add elements in listInteger */
        listInteger.add(3);
        listInteger.add(6);
        listInteger.add(4);
        listInteger.add(5);
        listInteger.add(1);
        listInteger.add(2);

        System.out.println("Initial Integer List: " + listInteger);
        /* Use Collections to sort a list */
        Collections.sort(listInteger);
        System.out.println("Sorted Integer List: " + listInteger);

        /* Create list of String */
        List listString = new ArrayList();
        /* Add elements in listString */
        listString.add("o");
        listString.add("i");
        listString.add("u");
        listString.add("e");
        listString.add("a");

        System.out.println("Initial String List: " + listString);
        /* Use Collections to sort a list */
        Collections.sort(listString);
        System.out.println("Sorted String List: " + listString);

        /* Create list of Object */
        List listMixed = new ArrayList();
        /* Add elements in listMixed */
        listMixed.add("u");
        listMixed.add("5");
        listMixed.add("a");
        listMixed.add("6");
        listMixed.add("1");
        listMixed.add("z");

        System.out.println("Initial Mixed List: " + listMixed);
        /* Use Collections to sort a list */
        Collections.sort(listMixed);
        System.out.println("Sorted Mixed List: " + listMixed);
    }
}

Output
Initial Integer List: [3, 6, 4, 5, 1, 2]
Sorted Integer List: [1, 2, 3, 4, 5, 6]

Initial String List: [o, i, u, e, a]
Sorted String List: [a, e, i, o, u]

Initial Mixed List: [u, 5, a, 6, 1, z]
Sorted Mixed List: [1, 5, 6, a, u, z]

  • Sorting Integer List: It'll sort integer values from lowest to highest (1,2,3...n).
  • Sorting String List: It'll sort string values from lowest to highest (a,b,c....z).
  • Sorting Mixed List: It'll sort integer values followed by string values (1,2,3...n,..a,b...z).

Difference between @include and jsp:include

Today we will understand the difference between <%@include file="header.jsp" %> and <jsp:include page="header.jsp"/>. Its important for Java developer to understand the basic difference and its one of the popular question asked in interviews.

<%@include file="header.jsp" %>

jsp include
Image gives you clear idea about <%@include %>. When you use <%@include %>, It will add page during the translation time of parent page. This will add file content of header.jsp as it is in index.jsp.


<jsp:include page="header.jsp"/>

jsp include
This image also gives you idea about <jsp:include />. When you use <jsp:include />, It will add page when user request for index.jsp. At the runtime header.jsp executed and result of page will be added in index.jsp page.