java


Java: Methods on how to iterate over a List

Following we present a few methods on how to iterate over a List in Java.

Currently we present:

  1. Using a standard for loop
  2. Using an iterator to loop
  3. Using a For-Each loop
  4. Using Streams
ListLooper.java (compressed) (0 downloads)
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

public class ListLooper {

    public static void main(final String[] argv) {

        final String elementsArray[] = new String[] { "First Element", "Second Element", "Third Element" };
        // First of all we convert an array of Strings to a list of Strings, we do this to avoid adding each element to the list we will use by using the add() method.
        final List<String> elementsList = Arrays.asList(elementsArray);

        // Method 1: Using a standard for loop
        System.out.println("Method 1: Using a standard for loop");
        // We will loop N times, where N is the size of the list.
        // Since the first element of the list is on position 0, we start from that and finish at position N-1.
        for (int i = 0; i < elementsList.size(); i++) {

            // Using get() we retrieve the element at position.
            System.out.println(elementsList.get(i));
        }

        // Method 2: Using an iterator to loop
        System.out.println("Method 2: Using an iterator to loop");
        // The Java iterator is an interface that belongs to the collection framework and allows us to traverse a collection and access the data element of the collection without bothering the user about the implementation details of that collection. 
        final Iterator<String> iterator = elementsList.iterator();
        while (iterator.hasNext()) {

            // next() returns the next element in the collection until the hasNext() method returns false.
            System.out.println(iterator.next());
        }

        // Method 3: Using a For-Each loop
        System.out.println("Method 3: Using a For-Each loop");
        // This code works for any object that implements the Iterable interface.
        for (final String element : elementsList) {

            System.out.println(element);
        }

        // Method 4: Using Streams
        System.out.println("Method 4: Using Streams");
        // This code will not work for Java versions earlier than Java 8.
        elementsList.forEach((element) -> {

            System.out.println(element);
        });
     }
}
ListLooper.java (compressed) (0 downloads)

Compilation and execution are presented in the next section.

javac ListLooper.java;

java ListLooper;
Method 1: Using a standard for loop
First Element
Second Element
Third Element
Method 2: Using an iterator to loop
First Element
Second Element
Third Element
Method 3: Using a For-Each loop
First Element
Second Element
Third Element
Method 4: Using Streams
First Element
Second Element
Third Element

Following is the Java version used in this article

java -version
openjdk version "1.8.0_111"
OpenJDK Runtime Environment (build 1.8.0_111-b16)
OpenJDK 64-Bit Server VM (build 25.111-b16, mixed mode)

Java: Automatically get Enum from String

The following code will create a static map that contains entries where the key would be the string representation of the enum enum.toString() and value would be the enum itself. This way you can retrieve an enum from its string representation using the static fromString() method.

public enum Type {

    ACCOUNT,
    CLIENT;

    public static Type fromString(final String name) {

        final Type element = sMap.get(name);
        if (element != null) {

            return element;
        }
        throw new IllegalArgumentException(String.format("Unknown value: <%s> for %s", name, Type.class.toString()));
    }

    private static final Map<String, Type> sMap = new HashMap<>();

    static {
        for (final Type t : Type.values()) {

            sMap.put(t.toString(), t);
        }
    }
}

For a more general solution, please checkout http://bytefreaks.net/programming-2/java/java-create-a-lookup-table-for-an-enum, that post will show you how to create a lookup table for any type of value (in contrast to using the enum.toString() method)


Java: Create a lookup table for an Enum 4

Simple Enum

Assuming the user has a simple enum that does not have any member variable as follows:

public enum Grades {
    A, B, C, D, E, F
}

In this case, we do not need to create a map to get an enum value from an input string. We can use the enum build-in method valueOf which returns the enum constant of the specified enum type with the specified name.

Please note that the input string must match exactly an identifier used to declare an enum constant in this type. Extraneous white-space characters or wrong letter case are not permitted.

An Enum that has a member variable

Switching to a more interesting example, we assume the user has an enum type that each enum constant has a member variable. In the following example each constant has an int value as member.

public enum Weekday {

    MONDAY(1),
    TUESDAY(2),
    WEDNESDAY(3),
    THURSDAY(4),
    FRIDAY(5),
    SATURDAY(6),
    SUNDAY(7);

    public int getCode() {

        return mCode;
    }

    Weekday(final int code) {

        mCode = code;
    }

    private final int mCode;
}

In this example, getting the matching enum constant for an input integer number is not as straight forward as before. We could iterate over all constants check their code and return the one that matches but that would not be efficient, especially for enum types that have many constants.

What we propose is to create a static map of elements that will have on the key part the value of the enum constant and on the value part the actual enum constant.

public enum Weekday {

    MONDAY(1),
    TUESDAY(2),
    WEDNESDAY(3),
    THURSDAY(4),
    FRIDAY(5),
    SATURDAY(6),
    SUNDAY(7);

    public int getCode() {

        return mCode;
    }

    public static Weekday fromCode(final int code) {

        final Weekday element = sMap.get(code);
        if (element != null) {

            return element;
        }
        throw new IllegalArgumentException(String.format("Unknown code: <%d> for %s", code, Weekday.class.toString()));
    }

    Weekday(final int code) {

        mCode = code;
    }

    private static final Map<Integer, Weekday> sMap = new HashMap<>();

    static {
        for (final Weekday d : Weekday.values()) {

            sMap.put(d.getCode(), d);
        }
    }
    private final int mCode;
}

What we did in the above code, was to statically create the map we described. Which is, a map from the value that each enum constant holds to the constant. Then using the fromCode method we defined, we check the map for the input value, if the value is not part of the keys set of the map, it will throw an Illegal Argument Exception.

Doing Even better

An improvement we could do in the above code, would be to extract the part of the code that iterates over the fields and creates the map to reuse it. To do that, we need to use Functional Interface. Meaning we will create a function that takes as input another function that expects some input (if any) and produces as output an element of the type of the key.

Our function that can be used for all enums that their constants hold an int value is the following:

//ToIntFunction represents a function that produces an int-valued result. This is the int-producing primitive specialization for Function. This is a functional interface whose functional method is applyAsInt(Object).
public static <E extends Enum<E>> Map<Integer, E> createMap(final ToIntFunction<E> converter, final Class<E> enumClass) {

    final Map<Integer, E> map = new HashMap<>();
    for (final E s : enumClass.getEnumConstants()) {

        map.put(converter.applyAsInt(s), s);
    }
    return map;
}

The code of the enum could change to the following:

public enum Weekday {

    MONDAY(1),
    TUESDAY(2),
    WEDNESDAY(3),
    THURSDAY(4),
    FRIDAY(5),
    SATURDAY(6),
    SUNDAY(7);

    public int getCode() {

        return mCode;
    }

    public static Weekday fromCode(final int code) {

        final Weekday element = sMap.get(code);
        if (element != null) {

            return element;
        }
        throw new IllegalArgumentException(String.format("Unknown code: <%d> for %s", code, Weekday.class.toString()));
    }

    Weekday(final int code) {

        mCode = code;
    }

    private static final Map<Integer, Weekday> sMap = Collections.unmodifiableMap(createMap(Weekday::getCode, Weekday.class));

    private final int mCode;
}

The function that we used as input to the new function is the getCode we defined in the enum. As you can see, it is a function that produces an int-valued result just as the requirement of the ToIntFunction parameter asks for.


Java: Breakdown a long number to the powers of two it is composed from 1

The following function will accept a long number as input and will produce an LongStream, which is a sequence of primitive long-valued elements that supports sequential and parallel aggregate operations.

public static LongStream splitToPowersOfTwo(final long input) {

    long temp = input;
    final LongStream.Builder builder = LongStream.builder();

    while (temp != 0) {

        //Long.lowestOneBit: Finds the lowest-order ("rightmost") one-bit in the specified long value and returns a long number that has only the bit in the previously matched position set as 1. This value is a power of two that is one of the components of the number. If the number is zero, the function returns zero.
        final long powerOfTwo = Long.lowestOneBit(temp);
        builder.add(powerOfTwo);
        //We update our temp by subtracting the number we got, our goal is to remove the previously matched bit and get the next one on the next iteration.
        temp = temp & ~ powerOfTwo;
    }

    return builder.build();
}

We used Long.lowestOneBit as it makes it easy for us to breakdown the number to its power of two components by matching for us only one bit at time.

Example of usage:

Scenario: We want to breakdown a long number to the powers of two that their sum produces the number and create a String with those values. Using our function, we can do the following:

final String output = splitToPowersOfTwo(flags).mapToObj(Long::toString).collect(Collectors.joining(", "));

Note: an LongStream is not the same as a Stream<Long>, we used .mapToObj(Long::toString) which calls the static method Long.toString(long). This is different to calling .map(Long::toString) on a Stream<Long> as the latter won’t compile because it is ambiguous.


Java: Breakdown an integer to the powers of two it is composed from 1

The following function will accept an integer number as input and will produce an IntStream, which is a sequence of primitive int-valued elements that supports sequential and parallel aggregate operations.

public static IntStream splitToPowersOfTwo(final int input) {

    int temp = input;
    final IntStream.Builder builder = IntStream.builder();

    while (temp != 0) {

        //Integer.lowestOneBit: Finds the lowest-order ("rightmost") one-bit in the specified int value and returns an int number that has only the bit in the previously matched position set as 1. This value is a power of two that is one of the components of the number. If the number is zero, the function returns zero.
        final int powerOfTwo = Integer.lowestOneBit(temp);
        builder.add(powerOfTwo);
        //We update our temp by subtracting the number we got, our goal is to remove the previously matched bit and get the next one on the next iteration.
        temp = temp & ~ powerOfTwo;
    }

    return builder.build();
}

We used Integer.lowestOneBit as it makes it easy for us to breakdown the number to its power of two components by matching for us only one bit at time.

Example of usage:

Scenario: We want to breakdown an integer to the powers of two that their sum produces the number and create a String with those values. Using our function, we can do the following:

final String output = splitToPowersOfTwo(flags).mapToObj(Integer::toString).collect(Collectors.joining(", "));

Note: an IntStream is not the same as a Stream<Integer>, we used .mapToObj(Integer::toString) which calls the static method Integer.toString(int). This is different to calling .map(Integer::toString) on a Stream<Integer> as the latter won’t compile because it is ambiguous.


Java: Given a path to a file, create the folders to it

Assuming you have a full path to a file you want to create but the folder to it might exist or not, you can use the following code in your program to check if the folder exists and if it doesn’t, create it.

//The file we want to create;
final String logFileName = "./someFolder/anotherFolder/etc/myFile.txt";
//We find the last occurrence of the File.separator value, which will allow us to separate the path from the filename
final int lastIndex = logFileName.lastIndexOf(File.separator);
//The actual path we want to make sure it exists
final String dirPath = logFileName.substring(0, lastIndex > 0 ? lastIndex : logFileName.length());
//We try to use the folder by assigning it to a File object
final File theDir = new File(dirPath);
//Make the check that the folder exists
if (!theDir.exists()) {
    //If the folder does not exist, create it
    theDir.mkdirs();
}
//Continue with execution

On-screen clock/count down/counter (version 3, Java)

We ported the original watch from AutoHotKey to Java.

UPDATE: Click here  Watch v3 - Windows executable (171 downloads) to download the application with a Windows launcher.

You can download the Java Jar version from this link : Watch v3.0 Java (205 downloads)

It started being used in the 106th IEEE Region 8 Committee Meeting that was held at the Fairmont Monte Carlo in Monaco on 19-20 of March 2016.

Key features

  • You can change the icon that appears in the task bar by placing an gif file with the name watch.gif in the config directory of the executable
  • You can drag the watch to a more convenient place with the mouse
  • You can move the watch using the arrow keys. Using the shift key it makes the movement more precise. Using the control key it makes the movement faster.
  • Double clicking on the watch it will hide it
  • Double clicking on the tray menu icon of the watch it will toggle it’s visibility
  • From the menu on the task bar you can “Set it on top”, allow mouse to click through the clock, hide/show the gui
  • You can set the color of the Font and the Color of the background using a color picker
  • You can set the transparency of the GUI
  • The tool has two modes, it can operate as a clock that shows time in 24 hour mode or AM/PM and can operate as a count down tool (timer)
  • The timer mode allows you to pause (and continue), reset and stop the time, reset and continue the time (using lap) or zero the clock

Good willed feedback is always welcome