How do I reverse the order of array elements?

In this code snippet you’ll learn how to reverse the order of array elements. To reverse to element order will be using the Collections.reverse() method. This method requires an argument with List type. Because of this we need to convert the array to a List type first. We can use the Arrays.asList() to do the conversion. And then we reverse it. To convert the List back to array we can use the Collection.toArray() method.

Let’s see the code snippet below:

package org.kodejava.util;

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

public class ArrayReverse {
    public static void main(String[] args) {
        // Creates an array of Integers and print it out.
        Integer[] numbers = {0, 1, 2, 3, 4, 5, 6, 7, 8};
        System.out.println("Arrays.toString(numbers) = " +
                Arrays.toString(numbers));

        // Convert the int arrays into a List.
        List<Integer> numberList = Arrays.asList(numbers);

        // Reverse the order of the List.
        Collections.reverse(numberList);

        // Convert the List back to array of Integers
        // and print it out.
        numberList.toArray(numbers);
        System.out.println("Arrays.toString(numbers) = " +
                Arrays.toString(numbers));
    }
}

The output of the code snippet above is:

Arrays.toString(numbers) = [0, 1, 2, 3, 4, 5, 6, 7, 8]
Arrays.toString(numbers) = [8, 7, 6, 5, 4, 3, 2, 1, 0]

How do I get all available currency codes?

The example presented in this code snippet show you how to get the available currency codes. We will need the locale information and use the Currency class for this example.

package org.kodejava.util;

import java.util.Currency;
import java.util.Locale;
import java.util.Map;
import java.util.TreeMap;

public class CurrencySymbolDemo {
    public static void main(String[] args) {
        CurrencySymbolDemo cs = new CurrencySymbolDemo();

        Map<String, String> currencies = cs.getAvailableCurrencies();
        for (String country : currencies.keySet()) {
            String currencyCode = currencies.get(country);
            System.out.println(country + " => " + currencyCode);
        }
    }

    /**
     * Get the currencies code from the available locales information.
     *
     * @return a map of currencies code.
     */
    private Map<String, String> getAvailableCurrencies() {
        Locale[] locales = Locale.getAvailableLocales();

        // We use TreeMap so that the order of the data in the map sorted
        // based on the country name.
        Map<String, String> currencies = new TreeMap<>();
        for (Locale locale : locales) {
            try {
                currencies.put(locale.getDisplayCountry(),
                        Currency.getInstance(locale).getCurrencyCode());
            } catch (Exception e) {
                // when the locale is not supported
            }
        }
        return currencies;
    }
}

You will have something like this printed on the screen:

...
Honduras => HNL
Hong Kong SAR China => HKD
Hungary => HUF
Iceland => ISK
India => INR
Indonesia => IDR
Iran => IRR
Iraq => IQD
Ireland => EUR
Isle of Man => GBP
...

How do I create a Locale object using a variant?

Font differences may force you to use different characters on different platforms. You could then define the Locale objects with the variant codes to identify those differences. The variant codes conform to no standard. They are arbitrary and specific to your application. If you create Locale objects with variant codes only your application will know how to deal with them.

In this example instead of demonstrating to use a different font for different platform we simplify it to just print a different message. We create three different resource bundles for each platform, the Birthday_fr_FR_UNIX.properties, Birthday_fr_FR_MAC.properties and Birthday_fr_FR_WIN.properties. These files will contains different message for each platform.

package org.kodejava.util;

import java.util.Locale;
import java.util.ResourceBundle;

public class LocalePlatform {
    public static void main(String[] args) {
        ResourceBundle res;
        String language = "fr";
        String country = "FR";

        // Construct a locale from language, country, variant. Where the variant
        // can be a variant vendor and browser specific code.
        Locale unix = new Locale(language, country, "UNIX");
        res = ResourceBundle.getBundle("Birthday", unix);
        System.out.println("UNIX: " + res.getString("birthday"));

        Locale mac = new Locale(language, country, "MAC");
        res = ResourceBundle.getBundle("Birthday", mac);
        System.out.println("MAC : " + res.getString("birthday"));

        Locale windows = new Locale(language, country, "WIN");
        res = ResourceBundle.getBundle("Birthday", windows);
        System.out.println("WIN : " + res.getString("birthday"));
    }
}

Here are the contents of the resource bundle files:

Birthday_fr_FR_UNIX.properties

birthday=Unix, Joyeux anniversaire à vous!

Birthday_fr_FR_MAC.properties

birthday=Mac, Joyeux anniversaire à vous!

Birthday_fr_FR_WIN.properties

birthday=Windows, Joyeux anniversaire à vous!

How do I get all available Locale language codes?

When you want to internationalize your application, you need to know the language code and country code. These codes will be used as the properties file name (the file name must be ended in language_COUNTRY.properties). Here is an example that show how to get all supported language’s code.

package org.kodejava.util;

import java.util.Locale;

public class LocaleCountryLanguageCode {
    public static void main(String[] args) {
        // Gets an array of all installed locales. The returned array represents
        // the union of locales supported by the Java runtime environment and by 
        // installed LocaleServiceProvider implementations.
        Locale[] locales = Locale.getAvailableLocales();

        for (Locale locale : locales) {
            System.out.printf("Locale name: %s = %s_%s%n",
                    locale.getDisplayName(), locale.getLanguage(), locale.getCountry());
        }
    }
}

Here are some of the results produces by the code above:

...
Locale name: Kikuyu (Latin, Kenya) = ki_KE
Locale name: Spanish (Brazil) = es_BR
Locale name: Koyra Chiini (Mali) = khq_ML
Locale name: English (Solomon Islands) = en_SB
Locale name: Tibetan (Tibetan, China) = bo_CN
Locale name: Cherokee (United States) = chr_US
Locale name: Kinyarwanda (Rwanda) = rw_RW
Locale name: Tachelhit (Tifinagh, Morocco) = shi_MA
Locale name: Arabic (Iraq) = ar_IQ
Locale name: Nyankole = nyn_
...

How do I use the SortedMap interface?

package org.kodejava.util;

import java.util.*;

public class SortedMapDemo {
    public static void main(String[] args) {
        SortedMap<String, String> sorted = new TreeMap<>();
        sorted.put("United States", "New York");
        sorted.put("United Kingdom", "London");
        sorted.put("Netherlands", "Amsterdam");
        sorted.put("Japan", "Tokyo");
        sorted.put("France", "Paris");

        // Gets the first(lowest) key currently in this map
        String firstKey = sorted.firstKey();

        // Gets the last (highest) key currently in this map
        String lastKey = sorted.lastKey();

        System.out.println("First key: " + firstKey);
        System.out.println("Last key : " + lastKey);

        // Gets a view of the portion of this map whose keys range
        // from fromKey(Japan), inclusive, to toKey(United Kingdom),
        // exclusive. (If fromKey and toKey are equal, the returned
        // map is empty.)
        SortedMap<String, String> sub = sorted.subMap("Japan",
                "United Kingdom");
        Set<String> subKeys = sub.keySet();
        System.out.println("\nSub Map: ");
        System.out.println("============");
        for (String key : subKeys) {
            System.out.println(key);
        }

        // Gets a view of the portion of this map whose keys are
        // strictly less than toKey(in this example is Netherlands)
        SortedMap<String, String> head = sorted.headMap("Netherlands");
        Set<String> headKeys = head.keySet();
        System.out.println("\nHead Map:");
        System.out.println("============");
        for (String key : headKeys) {
            System.out.println(key);
        }

        // Gets a view of the portion of this map whose keys are
        // strictly greater than or equal fromKey(in this example
        // is Netherlands)
        SortedMap<String, String> tail = sorted.tailMap("Netherlands");
        Set<String> tailKeys = tail.keySet();
        System.out.println("\nTail Map:");
        System.out.println("============");
        for (String key : tailKeys) {
            System.out.println(key);
        }
    }
}

Here is the output of the program:

First key: France
Last key : United States

Sub Map: 
============
Japan
Netherlands

Head Map:
============
France
Japan

Tail Map:
============
Netherlands
United Kingdom
United States

How do I convert a java.util.Vector into an array?

This example demonstrates how to convert a Vector object into an array. You can use the Vector.copyInto(Object[] array) method to create a copy of the Vector object in array form.

package org.kodejava.util;

import java.util.Vector;

public class VectorToArray {
    public static void main(String[] args) {
        Vector<Integer> vector = new Vector<>();
        vector.add(10);
        vector.add(20);
        vector.add(30);
        vector.add(40);
        vector.add(50);

        // Declares and initializes an Integer array.
        Integer[] numbers = new Integer[vector.size()];

        // Copies the components of this vector into the specified
        // array of Integer
        vector.copyInto(numbers);

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

The result of the code snippet above:

Number: 10
Number: 20
Number: 30
Number: 40
Number: 50

How do I remove elements from Deque?

This example shows you how to remove some elements from the Deque object. We can use the following methods for removing elements from Deque: remove(), remove(Object o), removeFirst(), removeLast().

package org.kodejava.util;

import java.util.Deque;
import java.util.LinkedList;

public class RemoveDequeDemo {
    public static void main(String[] args) {
        Deque<String> deque = new LinkedList<>();
        deque.add("A");
        deque.add("B");
        deque.add("C");
        deque.add("D");
        deque.add("E");
        deque.add("F");

        // Removes and retrieves the head of this Deque
        deque.remove();      // Removes "A"

        // Removes the first occurrence of element from this Deque
        deque.remove("F");   // Removes "F"

        // Retrieves and removes the first element of this deque
        deque.removeFirst(); // Removes "B"

        // Retrieves and removes the last element of this deque
        deque.removeLast();  // Removes "E"

        for (String item : deque) {
            System.out.println("Item = " + item);
        }
    }
}

How do I add elements into a Deque?

To add elements into a Deque object we can use the add(), addFirst() and addLast() method call.

package org.kodejava.util;

import java.util.Deque;
import java.util.LinkedList;

public class DequeAddElement {
    public static void main(String[] args) {
        // Create an instance of Deque using LinkedList class.
        Deque<String> deque = new LinkedList<>();

        // Insert a word into the Deque
        deque.add("jumps");

        // Insert words at the beginning of the current Deque
        // elements
        deque.addFirst("fox");
        deque.addFirst("brown");
        deque.addFirst("quick");
        deque.addFirst("The");

        // Insert words at the end of the current Deque elements
        deque.addLast("over");
        deque.addLast("the");
        deque.addLast("lazy");
        deque.addLast("dog");

        for (String word : deque) {
            System.out.println("Word = " + word);
        }
    }
}

Here is the output:

Word = The
Word = quick
Word = brown
Word = fox
Word = jumps
Word = over
Word = the
Word = lazy
Word = dog

How do I create a java.util.Hashtable and iterates its contents?

The code snippet shows you how to create and instance of Hashtable that stores Integer values using a String keys. After that we iterate the elements of the Hashtable using the Enumeration interface.

package org.kodejava.util;

import java.util.Enumeration;
import java.util.Hashtable;

public class HashtableDemo {
    public static void main(String[] args) {
        // Creates an instance of Hashtable
        Hashtable<String, Integer> numbers = new Hashtable<>();
        numbers.put("one", 1);
        numbers.put("two", 2);
        numbers.put("three", 3);

        // Returns an enumeration of the keys in this Hashtable
        Enumeration<String> keys = numbers.keys();
        while (keys.hasMoreElements()) {
            // Returns the next element of this enumeration if this
            // enumeration object has at least one more element to
            // provide
            String key = keys.nextElement();
            System.out.printf("Key: %s, Value: %d%n", key, numbers.get(key));
        }
    }
}

How do I create Deque using ArrayDeque class?

This example show you how to create a Deque using the ArrayDeque implementation. The ArrayDeque stores its elements using an array. If the number of elements exceeds the space in the array, a new array will be allocated, and all elements moved the new allocated array.

In the code below we initiate the size of the Deque to store five elements. When we add the element number six the array that stores the elements of the Deque will be resized.

package org.kodejava.util;

import java.util.ArrayDeque;
import java.util.Deque;

public class ArrayDequeDemo {
    public static void main(String[] args) {
        // Constructs an empty array deque with an initial capacity
        // sufficient to hold the specified number of elements.
        Deque<Integer> deque = new ArrayDeque<>(5);
        deque.add(1);
        deque.add(1);
        deque.add(2);
        deque.add(3);
        deque.add(5);
        deque.add(8);
        deque.add(14);
        deque.add(22);

        for (Integer number : deque) {
            System.out.println("Number = " + number);
        }
    }
}