How to check is there any common element between two List of String?

Java Collection Framework disjoint


Collections.disjoint(Collection<?> c1, Collection<?> c2)
Returns true if the two specified collections have no elements in common.

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

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

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

        /* Create list of String */
        List<String> listStringSecond = new ArrayList<String>();
        /* Add elements in listString */
        listStringSecond.add("x");
        listStringSecond.add("y");
        listStringSecond.add("z");

        System.out.println("Initial List 1: " + listString);
        System.out.println("Initial List 2: " + listStringSecond);
        System.out.println("------------------------");
        System.out.println("Disjoint: " + Collections.disjoint(listString, listStringSecond));

        /* Add element available in listString */
        listStringSecond.add("a");
        System.out.println("------------------------");
        System.out.println("List 2 after add(\"a\"): " + listStringSecond);
        System.out.println("Disjoint after add(\"a\"): " + Collections.disjoint(listString, listStringSecond));
    }
}

Output
Initial List 1: [a, b, c]
Initial List 2: [x, y, z]
------------------------
Disjoint: true
------------------------
List 2 after add("a"): [x, y, z, a]
Disjoint after add("a"): false

How to reverse List in Java Collection Framework?

Collections Framework Reverse Java


List allows to add String and Custom bean elements in it. To reverse the given list we can use Collections.reverse(List<?> list).

Source Code
/**
 * @author javaQuery
 */
public class User{

    private String Firstname;
    private String Lastname;

    public String getFirstname() {
        return Firstname;
    }

    public void setFirstname(String Firstname) {
        this.Firstname = Firstname;
    }

    public String getLastname() {
        return Lastname;
    }

    public void setLastname(String Lastname) {
        this.Lastname = Lastname;
    }
}
import com.javaquery.beans.User;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

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

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

        System.out.println("Initial List");
        System.out.println(listString);
        System.out.println("------------------------");

        Collections.reverse(listString);
        System.out.println("Reverse List");
        System.out.println(listString);
        System.out.println("------------------------");

        /* Create object of User */
        User user1 = new User();
        /* Set Firstname of User */
        user1.setFirstname("Vicky");
        /* Set Lastname of User */
        user1.setLastname("Thakor");

        User user2 = new User();
        user2.setFirstname("Chirag");
        user2.setLastname("Thakor");

        User user3 = new User();
        user3.setFirstname("Heer");
        user3.setLastname("Thakor");
        
        /* Add Users in List<User> */
        List<User> listUser = new ArrayList<User>();
        /* Add elements in listUser */
        listUser.add(user1);
        listUser.add(user2);
        listUser.add(user3);

        System.out.println("Initial List");
        System.out.println("------------------------");
        for (User user : listUser) {
            System.out.println(user.getFirstname() + " " + user.getLastname());
        }
        System.out.println("------------------------");
        System.out.println("Reverse List");
        System.out.println("------------------------");
        Collections.reverse(listUser);
        for (User user : listUser) {
            System.out.println(user.getFirstname() + " " + user.getLastname());
        }        
    }
}

Output
[a, b, c]
------------------------
Reverse List
[c, b, a]
------------------------
Initial List
------------------------
Vicky Thakor
Chirag Thakor
Heer Thakor
------------------------
Reverse List
------------------------
Heer Thakor
Chirag Thakor
Vicky Thakor

How to sort List of Bean in Java?

Collection Framework Sort


In my previous article How to sort a List in Java? We have seen how we can sort List<String>. This time we'll understand code of How we can sort List<Bean>.

Storing data in bean is common practice in current industry. Bean structure allows us to get specific property of object. Hope you all are aware of what is bean so lets not waste time and understand the code.

Background
We have User object that holds two property Firstname and Lastname. We will sort the List on Firstname in ascending order. There are two technique you can use to sort an object and we'll checkout one by one.

Technique One
Say you have access to your bean class and can modify the class file then by implementing Comparable interface you can perform sorting.
/**
 * @author javaQuery
 */
public class User implements Comparable<User> {

    private String Firstname;
    private String Lastname;

    public String getFirstname() {
        return Firstname;
    }

    public void setFirstname(String Firstname) {
        this.Firstname = Firstname;
    }

    public String getLastname() {
        return Lastname;
    }

    public void setLastname(String Lastname) {
        this.Lastname = Lastname;
    }

    /**
     * This `compareTo` used to compare two `User` object,
     * Which internally uses `compareTo` of String class to compare two String values.
     * @param obj
     * @return 
     */
    @Override
    public int compareTo(User obj) {
        /* Check object and Firstname are not null */
        if(obj != null && obj.Firstname != null){
            /* We will use `compareTo` of String class */
            /* For ascending order */
            return this.Firstname.compareTo(obj.Firstname);
   
            /* For descending order */
            /* return obj.Firstname.compareTo(this.Firstname) */
        }else{
            return -1;
        }
    }
 
 /* If you want to sort on `int` value then uncomment following code */
//   @Override
//    public int compareTo(User obj) {
//        /* Check object and id is not null and 0 */
//        if (obj != null && obj.getId() != 0) {
//            /* For ascending order */
//            return this.getId() - obj.getId();
//
//            /* For descending order */
//            /* return obj.getId() - this.getId(); */
//        } else {
//            return -1;
//        }
//    }
}
Source Code
import com.javaquery.beans.User;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

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

    public static void main(String[] args) {
        /* Create object of User */
        User user1 = new User();
        /* Set Firstname of User */
        user1.setFirstname("Vicky");
        /* Set Lastname of User */
        user1.setLastname("Thakor");

        User user2 = new User();
        user2.setFirstname("Chirag");
        user2.setLastname("Thakor");

        User user3 = new User();
        user3.setFirstname("Heer");
        user3.setLastname("Thakor");

        User user4 = new User();
        user4.setFirstname("Yogita");
        user4.setLastname("Thakor");

        User user5 = new User();
        user5.setFirstname("Riddhi");
        user5.setLastname("Thakor");

        User user6 = new User();
        user6.setFirstname("Xender");
        user6.setLastname("Thakor");

        /* Add Users in List<User> */
        List<User> listUser = new ArrayList<User>();
        listUser.add(user4);
        listUser.add(user6);
        listUser.add(user1);
        listUser.add(user5);
        listUser.add(user2);
        listUser.add(user3);

        System.out.println("Initial List");
        System.out.println("------------------------");
        for (User user : listUser) {
            System.out.println(user.getFirstname() + " " + user.getLastname());
        }
        System.out.println("------------------------");

        Collections.sort(listUser);
        System.out.println("List after Collections.sort(List<T> list)");
        System.out.println("------------------------");
        for (User user : listUser) {
            System.out.println(user.getFirstname() + " " + user.getLastname());
        }
    }
}
Output of the above code is given at the end of the article as both technique gives same output.

Technique Two
Say if you don't have access to your bean(bind in jar) and still you want to sort on specific property then by creating custom Comparator you can achieve same.
/**
 * @author javaQuery
 */
public class User{

    private String Firstname;
    private String Lastname;

    public String getFirstname() {
        return Firstname;
    }

    public void setFirstname(String Firstname) {
        this.Firstname = Firstname;
    }

    public String getLastname() {
        return Lastname;
    }

    public void setLastname(String Lastname) {
        this.Lastname = Lastname;
    }
}
Source code
import com.javaquery.beans.User;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

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

    public static void main(String[] args) {
        /* Create object of User */
        User user1 = new User();
        /* Set Firstname of User */
        user1.setFirstname("Vicky");
        /* Set Lastname of User */
        user1.setLastname("Thakor");

        User user2 = new User();
        user2.setFirstname("Chirag");
        user2.setLastname("Thakor");

        User user3 = new User();
        user3.setFirstname("Heer");
        user3.setLastname("Thakor");

        User user4 = new User();
        user4.setFirstname("Yogita");
        user4.setLastname("Thakor");

        User user5 = new User();
        user5.setFirstname("Riddhi");
        user5.setLastname("Thakor");

        User user6 = new User();
        user6.setFirstname("Xender");
        user6.setLastname("Thakor");

        /* Add Users in List<User> */
        List<User> listUser = new ArrayList<User>();
        listUser.add(user4);
        listUser.add(user6);
        listUser.add(user1);
        listUser.add(user5);
        listUser.add(user2);
        listUser.add(user3);

        System.out.println("Initial List");
        System.out.println("------------------------");
        for (User user : listUser) {
            System.out.println(user.getFirstname() + " " + user.getLastname());
        }
        System.out.println("------------------------");

        /* Create object of `SortingObjectListExample` */
        SortingObjectListExample objSortingObjectListExample = new SortingObjectListExample();
        /* Get custom Comparator */
        Comparator<User> objComparator = objSortingObjectListExample.getComparator();

        /* Sort List<User> using custom Comparator */
        Collections.sort(listUser, objComparator);
        System.out.println("List after Collections.sort(List<T> list)");
        System.out.println("------------------------");
        for (User user : listUser) {
            System.out.println(user.getFirstname() + " " + user.getLastname());
        }
    }

    /* Create custom Comparator */
    public Comparator<User> getComparator() {
        return new Comparator<User>() {

            @Override
            public int compare(User obj1, User obj2) {
                /* Check obj1 and obj2 are not null and also check Firstname of both objects are not null */
                if (obj1 != null && obj2 != null
                        && obj1.getFirstname() != null && obj2.getFirstname() != null) {
                    /* Use `compareTo` of String class to compare two String values */
                    /* For ascending order */
                    return obj1.getFirstname().compareTo(obj2.getFirstname());
   
                    /* For descending order */
                    /* return obj2.getFirstname().compareTo(obj1.getFirstname()) */
                } else {
                    return -1;
                }
            }
        };
    }
}
Output
Initial List
------------------------
Yogita Thakor
Xender Thakor
Vicky Thakor
Riddhi Thakor
Chirag Thakor
Heer Thakor
------------------------
List after Collections.sort(List<T> list)
------------------------
Chirag Thakor
Heer Thakor
Riddhi Thakor
Vicky Thakor
Xender Thakor
Yogita Thakor

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.