Java


Java: remove leading character (or any prefix) from String only if it matches 1

The following snippet allows you to check if a String in Java starts with a specific character (or a specific prefix) that you are looking for and remove it.
To keep the number of lines small, we used the Java ?: ternary operator, which defines a conditional expression in a compact way.
Then, to quickly check if the first character(s) is the one we are looking for before removing it we used the String.startsWith().
To compute the number of characters to remove we used the String.length() on the needle.
Finally, to strip the leading character(s) we used String.substring() whenever the prefix matched.


final String needle = "//";
final int needleSize = needle.length();
String haystack = "";
haystack = haystack.startsWith(needle) ? haystack.substring(needleSize) : haystack;
System.out.print(haystack);

haystack = "apple";
haystack = haystack.startsWith(needle) ? haystack.substring(needleSize) : haystack;
System.out.println(haystack);

haystack = "//banana";
haystack = haystack.startsWith(needle) ? haystack.substring(needleSize) : haystack;
System.out.println(haystack);

The above code will result in the following:


apple
banana

 

Bonus: to remove all the instances of a character anywhere in a string:


final String needle = "a";
final int needleSize = needle.length();
String haystack = "banana";
haystack = haystack.replace(needle,"");
System.out.println(haystack);

The above code will result in the following:

bnn

Bonus: to remove the first instance of a character anywhere in a string:


final String needle = "a";
final int needleSize = needle.length();
String haystack = "banana";
haystack = haystack.replaceFirst(needle,"");
System.out.println(haystack);

The above code will result in the following:

bnana

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

[download id=”2234″]

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);
        });
     }
}

[download id=”2234″]

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)