How do I convert java.util.Set into Array?

package org.kodejava.util;

import java.util.*;

public class SetToArray {
    public static void main(String[] args) {
        // Create a java.util.Set object and add some integers into the Set.
        Set<Integer> numberSet = new HashSet<>();
        numberSet.add(1);
        numberSet.add(2);
        numberSet.add(3);
        numberSet.add(5);
        numberSet.add(8);

        // Converting a java.util.Set into an array can be done by creating a
        // java.util.List object from the Set and then convert it into an array
        // by calling the toArray() method on the list object.
        List<Integer> numberList = new ArrayList<>(numberSet);
        Integer[] numbers = numberList.toArray(new Integer[0]);

        // Display the content of numbers array.
        for (int i = 0; i < numbers.length; i++) {
            Integer number = numbers[i];
            System.out.print(number + (i < numbers.length - 1 ? ", " : "\n"));
        }

        // Display the content of numbers array using the for-each loop.
        for (Integer number : numbers) {
            System.out.print(number + ", ");
        }
    }
}

How do I convert LinkedList to array?

package org.kodejava.util;

import java.util.LinkedList;
import java.util.List;

public class LinkedListToArray {
    public static void main(String[] args) {
        List<String> list = new LinkedList<>();
        list.add("Blue");
        list.add("Green");
        list.add("Purple");
        list.add("Orange");

        // Converting LinkedList to array can be done by calling the toArray()
        // method of the List;
        String[] colors = new String[list.size()];
        list.toArray(colors);

        for (String color : colors) {
            System.out.println("color = " + color);
        }
    }
}

How do I sort array values in case-insensitive order?

By default, when sorting an arrays the value will be ordered in case-sensitive order. This example show you how to order it in case-insensitive order.

package org.kodejava.util;

import java.util.Arrays;

public class SortArrayCaseSensitivity {
    public static void main(String[] args) {
        String[] teams = new String[5];
        teams[0] = "Manchester United";
        teams[1] = "chelsea";
        teams[2] = "Arsenal";
        teams[3] = "liverpool";
        teams[4] = "EVERTON";

        // Sort array, by default it will be sorted in case-sensitive order.
        // [Arsenal, EVERTON, Manchester United, chelsea, liverpool]
        Arrays.sort(teams);
        System.out.println("Case sensitive  : " + Arrays.toString(teams));

        // Sort array in case-insensitive order
        // [Arsenal, chelsea, EVERTON, liverpool, Manchester United]
        Arrays.sort(teams, String.CASE_INSENSITIVE_ORDER);
        System.out.println("Case insensitive: " + Arrays.toString(teams));
    }
}

The result of the code snippet above:

Case sensitive  : [Arsenal, EVERTON, Manchester United, chelsea, liverpool]
Case insensitive: [Arsenal, chelsea, EVERTON, liverpool, Manchester United]

How do I remove duplicate element from array?

This example demonstrates you how to remove duplicate elements from an array using the help of java.util.HashSet class.

package org.kodejava.util;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class ArrayRemoveDuplicate {
    public static void main(String[] args) {
        // A string array with duplicate values.
        String[] data = {"A", "C", "B", "D", "A", "B", "E", "D", "B", "C"};
        System.out.println("Original array         : " + Arrays.toString(data));

        // Convert a string array into java.util.List because we need a list
        // object to create the java.util.Set object.
        List<String> list = Arrays.asList(data);

        // A set is a collection object that cannot have a duplicate values,
        // by converting the array to a set the duplicate value will be removed.
        Set<String> set = new HashSet<>(list);

        // Convert the java.util.Set back to array using the toArray() method of
        // the set object copy the value in the set to the defined array.
        String[] result = set.toArray(new String[0]);
        System.out.println("Array with no duplicate: " + Arrays.toString(result));
    }
}

The result of the code snippet above:

Original array         : [A, C, B, D, A, B, E, D, B, C]
Array with no duplicate: [A, B, C, D, E]

How do I convert Array to java.util.Set?

package org.kodejava.util;

import java.util.*;

public class ArrayToSetExample {
    public static void main(String[] args) {
        Integer[] numbers = {7, 7, 8, 9, 10, 8, 8, 9, 6, 5, 4};

        // To convert an array into a java.util.Set firstly we need to convert the
        // array into a java.util.List using the Arrays.asList() method. With the
        // List object created we can instantiate a new java.util.HashSet and pass
        // the list as the constructor parameter.
        List<Integer> numberList = Arrays.asList(numbers);
        Set<Integer> numberSet = new HashSet<>(numberList);

        // Or we can simply combine the line above into single line.
        Set<Integer> anotherNumberSet = new HashSet<>(Arrays.asList(numbers));

        // Display what we get in the set using iterator.
        for (Iterator<Integer> iterator = numberSet.iterator(); iterator.hasNext(); ) {
            Integer number = iterator.next();
            System.out.print(number + ", ");
        }

        // Display what we get in the set using for-each.
        for (Integer number : anotherNumberSet) {
            System.out.print(number + ", ");
        }
    }
}

How do I convert varargs to an array?

Varargs can be seen as a simplification of array when we need to pass a multiple value as a method parameter. Varargs itself is an array that automatically created, for these reason you will be enabled to do things you can do with array to varargs.

In the example below you can see the messages parameter can be assigned to the String array variables, we can call the length method to the messages parameter as we do with the array. So actually you don’t need to convert varargs to array because varargs is array.

package org.kodejava.lang;

public class VarargsToArray {
    public static void main(String[] args) {
        printMessage("Hello ", "there", ", ", "how ", "are ", "you", "?");
    }

    public static void printMessage(String... messages) {
        String[] copiedMessage = messages;
        for (int i = 0; i < messages.length; i++) {
            System.out.print(copiedMessage[i]);
        }
    }
}

How do I create a method that accept varargs in Java?

Varargs (variable arguments) is a new feature in Java 1.5 which allows us to pass multiple values in a single variable name when calling a method. Of course, it can be done easily using array but the varargs add another power to the language.

The varargs can be created by using three periods (...) after the parameter type. If a method accept others parameter than the varargs, the varargs parameter should be the last parameter to the method. And please be aware that overloading a varargs method can make harder to figure out which method is called in the code.

package org.kodejava.lang;

import java.util.Arrays;

public class VarArgsExample {
    public static void main(String[] args) {
        VarArgsExample e = new VarArgsExample();
        e.printParams(1, 2, 3);
        e.printParams(10, 20, 30, 40, 50);
        e.printParams(100, 200, 300, 400, 500);
    }

    public void printParams(int... numbers) {
        System.out.println(Arrays.toString(numbers));
    }
}

Running the code snippet give you the following output:

[1, 2, 3]
[10, 20, 30, 40, 50]
[100, 200, 300, 400, 500]

How do I copy char array to string?

package org.kodejava.lang;

public class CharArrayCopyExample {
    public static void main(String[] args) {
        char[] data = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'};

        // Copy all value in the char array and create a new string out of it.
        String text = String.valueOf(data);
        System.out.println(text);

        // Copy a sub array from the char array and create a new string. The
        // following line will just copy 5 characters starting from array index
        // of 3. If the element copied is outside the array index an
        // IndexOutOfBoundsException will be thrown.
        text = String.copyValueOf(data, 3, 5);
        System.out.println(text);
    }
}

The result:

abcdefghij
defgh

How do I shuffle elements of an array?

package org.kodejava.util;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class ArrayShuffle {
    public static void main(String[] args) {
        // Initialize the contents of our array
        String[] alphabets = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J"};

        // As the Collections.shuffle() method need a list for the parameter
        // we convert our array into List using the Arrays class.
        List<String> list = Arrays.asList(alphabets);

        // Here we just simply used the shuffle method of Collections class
        // to shuffle out defined array.
        Collections.shuffle(list);

        // Run the code again and again, then you'll see how simple we do
        // shuffling
        for (String alpha : list) {
            System.out.print(alpha + " ");
        }
    }
}

An example of the generated results are:

F H E A B I G J D C  

How do I use for-each in Java?

Using for-each command to iterate arrays or a list can simplified our code. Below is an example how to do it in Java. The first loop is for iterating array and the second for iterating a list containing a some names.

package org.kodejava.lang;

import java.util.ArrayList;
import java.util.List;

public class ForEachExample {
    public static void main(String[] args) {
        Integer[] numbers = {10, 100, 1000, 10000, 100000, 1000000};

        for (Integer i : numbers) {
            System.out.println("Number: " + i);
        }

        List<String> names = new ArrayList<>();
        names.add("Musk");
        names.add("Nakamoto");
        names.add("Einstein");

        for (String name : names) {
            System.out.println("Name: " + name);
        }
    }
}

The result of the code snippet:

Number: 10
Number: 100
Number: 1000
Number: 10000
Number: 100000
Number: 1000000
Name: Musk
Name: Nakamoto
Name: Einstein