Showing posts with label Array. Show all posts

How to Initialize boolean or Boolean array in declaration?

Following excerpt show How you can Initialize boolean or Boolean array in its declaration.

Source code
public class InitializeBooleanArrayExample {
    public static void main(String[] args) {
        /* Declare and Initialize boolean Array */
        boolean[] booleanArray1 = {true, false};
        
        System.out.println("Print value of boolean[]");
        /* Print value of array */
        for (boolean b : booleanArray1) {
            System.out.println(b);
        }
        
        /**
         * Declare and Initialize Boolean Array.
         * Boolean can hold `null` values.
         */
        Boolean booleanArray2[] = {true, false, null};
        
        System.out.println("Print value of Boolean[]");
        /* Print value of array */
        for (Boolean b : booleanArray2) {
            System.out.println(b);
        }
    }
}

Output
Print value of boolean[]
true
false
Print value of Boolean[]
true
false
null

References
How to Initialize int or Integer array in declaration?
How to Initialize float or Float array in declaration?
How to Initialize long or Long array in declaration?
How to Initialize double or Double array in declaration?

How to Initialize double or Double array in declaration?

Following excerpt show How you can Initialize double or Double array in its declaration.

Source code
public class InitializeDoubleArrayExample {
    public static void main(String[] args) {
        /* Declare and Initialize double Array */
        double[] doubleArray1 = {10.1D, 20.2D, 30.3D};
        
        System.out.println("Print value of double[]");
        /* Print value of array */
        for (double d : doubleArray1) {
            System.out.println(d);
        }
        
        /**
         * Declare and Initialize Double Array.
         * Double can hold `null` values.
         */
        Double doubleArray2[] = {10.1D, 20.2D, null};
        
        System.out.println("Print value of Double[]");
        /* Print value of array */
        for (Double d : doubleArray2) {
            System.out.println(d);
        }
    }
}

Output
Print value of double[]
10.1
20.2
30.3
Print value of Double[]
10.1
20.2
null

References
How to Initialize int or Integer array in declaration?
How to Initialize float or Float array in declaration?
How to Initialize long or Long array in declaration?
How to Initialize boolean or Boolean array in declaration?

How to Initialize long or Long array in declaration?

Following excerpt show How you can Initialize long or Long array in its declaration.

Source code
public class InitializeLongArrayExample {
    public static void main(String[] args) {
        /* Declare and Initialize long Array */
        long longArray1[] = {10L, 20L, 30L};
        
        System.out.println("Print value of long[]");
        /* Print value of array */
        for (long l : longArray1) {
            System.out.println(l);
        }
        
        /**
         * Declare and Initialize Long Array.
         * Long can hold `null` values.
         */
        Long longArray2[] = {10L, 20L, null};
        
        System.out.println("Print value of Long[]");
        /* Print value of array */
        for (Long l : longArray2) {
            System.out.println(l);
        }
    }
}

Output
Print value of long[]
10
20
30
Print value of Long[]
10
20
null

References
How to Initialize int or Integer array in declaration?
How to Initialize float or Float array in declaration?
How to Initialize double or Double array in declaration?
How to Initialize boolean or Boolean array in declaration?

How to Initialize float or Float array in declaration?

Following excerpt show How you can Initialize float or Float array in its declaration.

Source code
public class InitializeFloatArrayExample {
    public static void main(String[] args) {
        /* Declare and Initialize float Array */
        float[] floatArray1 = {10.1f, 20.2f, 30.3f};
        
        System.out.println("Print value of float[]");
        /* Print value of array */
        for (float f : floatArray1) {
            System.out.println(f);
        }
        
        /**
         * Declare and Initialize Float Array.
         * Float can hold `null` values.
         */
        Float floatArray2[] = {10.1f, 20.2f, null};
        
        System.out.println("Print value of Float[]");
        /* Print value of array */
        for (Float f : floatArray2) {
            System.out.println(f);
        }
    }
}

Output
Print value of float[]
10.1
20.2
30.3
Print value of Float[]
10.1
20.2
null

References
How to Initialize int or Integer array in declaration?
How to Initialize long or Long array in declaration?
How to Initialize double or Double array in declaration?
How to Initialize boolean or Boolean array in declaration?

How to Initialize int or Integer array in declaration?

Following excerpt show How you can Initialize int or Integer array in its declaration.

Source code
public class InitializeIntArrayExample {
    public static void main(String[] args) {
        /* Declare and Initialize int Array */
        int intArray[] = {10, 20, 30};
        
        System.out.println("Print value of int[]");
        /* Print value of array */
        for (int i : intArray) {
            System.out.println(i);
        }
        
        /**
         * Declare and Initialize Integer Array.
         * Integer can hold `null` values.
         */
        Integer integerArray[] = {10, 20, null};
        
        System.out.println("Print value of Integer[]");
        for (Integer i : integerArray) {
            System.out.println(i);
        }
    }
}

Output
Print value of int[]
10
20
30
Print value of Integer[]
10
20
null

References
How to Initialize float or Float array in declaration?
How to Initialize long or Long array in declaration?
How to Initialize double or Double array in declaration?
How to Initialize boolean or Boolean array in declaration?

How to sort Array in Ascending, Descending and Mixed mode in Java?

java.util.Arrays
java.util.Arrays class provides many options for sorting an Array. We will sort Array in Ascending, Descending and Mixed mode(1st/first to kth in Ascending order and k+1th to nth/last in Descending order, you can choose different position for 1st,kth and nth).

In addition this question was asked in leading Multi National Company(MNC). Its worth understanding code for future interview of yours.

Source Code
public class SortArray {

    public static void main(String[] args) {
        Integer[] intSortArrayAscending = {25, 9, 23, 1, 4, 90, 99};
        Integer[] intSortArrayDescending = {25, 9, 23, 1, 4, 90, 99};
        Integer[] intSortArrayMixedMode = {25, 9, 23, 1, 4, 90, 99};

        /* Sort Array in Ascending order */
        Arrays.sort(intSortArrayAscending);
        
        /* Print array */
        System.out.print("Ascending order: ");
        for (int i : intSortArrayAscending) {
            System.out.print(i + ",");
        }

        System.out.println("\n------------------------");

        /* Sort Array in Descending order */
        SortArray objSortArray = new SortArray();
        /* Use Comparator to sort Array in Descending order */
        Arrays.sort(intSortArrayDescending, objSortArray.comparatorDescending());

        /* Print array */
        System.out.print("Descending order: ");
        for (int i : intSortArrayDescending) {
            System.out.print(i + ",");
        }
        System.out.println("\n------------------------");

        System.out.println("Mixed mode sorting:");
        /**
         * Mixed mode Sorting
         * Sort 1st/first position to kth in Ascending order
         * and
         * Sort k+1th position to nth/last in Descending order
         */
        
        /* I used middle point as pivotPoint */
        int pivotPosition = intSortArrayMixedMode.length / 2;
        System.out.println("Ascending order from element 1 to " + pivotPosition);
        System.out.println("Descending order from element " + (pivotPosition + 1) + " to " + intSortArrayMixedMode.length);

        /* Arrays.sort(int[] a, int fromIndex, int toIndex) */
        Arrays.sort(intSortArrayMixedMode, 0, pivotPosition);

        /*  sort(T[] a, int fromIndex, int toIndex, Comparator<? super T> c) */
        Arrays.sort(intSortArrayMixedMode, pivotPosition, intSortArrayMixedMode.length, objSortArray.comparatorDescending());

        /* Print array */
        for (int i : intSortArrayMixedMode) {
            System.out.print(i + ",");
        }
    }

    /**
     * Comparator for Descending order
     */
    public Comparator<Integer> comparatorDescending() {
        return new Comparator<Integer>() {

            @Override
            public int compare(Integer o1, Integer o2) {
                if (o1 < o2) {
                    return 1;
                } else {
                    return -1;
                }
            }
        };
    }
}

Output
Ascending order: 1,4,9,23,25,90,99,
------------------------
Descending order: 99,90,25,23,9,4,1,
------------------------
Mixed mode sorting:
Ascending order from element 1 to 3
Descending order from element 4 to 7
9,23,25,99,90,4,1,


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