Some simple utility methods I use a lot in Java

Whenever I start a new project in Java I always find myself in need of some basic utility methods that are lacking in the standard library. I suppose that every programmer has his own little “bag of tricks” for every language (well, maybe not for python.. ❤ ).. and this is mine!

These are only some of the methods I use the most, of course, those that may be useful for many people 🙂

/*
 * This program is free software. It comes without any warranty, to
 * the extent permitted by applicable law. You can redistribute it
 * and/or modify it under the terms of the Do What The Fuck You Want
 * To Public License, Version 2, as published by Sam Hocevar. See
 * http://sam.zoy.org/wtfpl/COPYING for more details.
 */

import java.util.List;
import java.util.Set;

/**
 * Contains only a bunch of <code>static</code> utility methods.
 *
 * @author mb - somethingididnotknow.wordpress.com
 */
public final class Utilities {

    /**
     * Checks whether <strong>all</strong> the provided objects are
     * <code>null</code>.
     *
     * @param objects
     *            a number of objects of any kind that are to be checked
     *            against <code>null</code>
     * @return <code>true</code> in case <strong>all</strong> the argument
     *         objects are <code>null</code>, <code>false</code> otherwise.
     */
    public static boolean areAllNull(Object... objects) {
        for (Object o : objects) {
            if (o != null)
                return false;
        }
        return true;
    }

    /**
     * Checks whether <strong>any</strong> of the argument objects is
     * <code>null</code>.
     *
     * @param objects
     *            a number of objects of any kind that are to be checked
     *            against <code>null</code>.
     * @return <code>true</code> if at least one of the arguments is
     *         <code>null</code>.
     */
    public static boolean isAnyNull(Object... objects) {
        for (Object o : objects) {
            if (o == null)
                return true;
        }
        return false;
    }

    /**
     * Checks whether the two arguments are equal using a <em>null-safe</em>
     * comparison.
     *
     * In case only one of the two objects is <code>null</code>,
     * <code>false</code> is returned. In case both are not <code>null</code>
     * {@link Object#equals(Object)} is called on the first object using the
     * second as argument.
     *
     * @param first
     *            the first object to be checked.
     * @param second
     *            the second object to be checked.
     * @return <code>true</code> in case {@link Object#equals(Object)} returns
     *         <code>true</code> or the objects are both <code>null</code>,
     *         <code>false</code> otherwise.
     */
    public static boolean nsEquals(Object first, Object second) {
        if (first == null)
            return second == null;
        if (second == null)
            return false;
        return first.equals(second);
    }

    /**
     * Returns a String that is empty in case the argument <tt>string</tt> is
     * <code>null</code>, the unmodified <tt>string</tt> otherwise.
     *
     * @param string
     *            the string to be checked against <code>null</code>
     * @return the empty String if <tt>string</tt> is <code>null</code>, the
     *         argument <tt>string</tt> unmodified otherwise
     */
    public static String nonNull(final String string) {
        return string == null ? "" : string;
    }

    /**
     * An equivalent of Python's <code>str.join()</code> function on lists: it
     * returns a String which is the concatenation of the strings in the
     * argument array. The separator between elements is the argument
     * <tt>toJoin</tt> string. The separator is only inserted between
     * elements: there's no separator before the first element or after the
     * last.
     *
     * @param toJoin
     *            the separator, if <code>null</code> the empty String is used
     * @param list
     *            a list of <code>Object</code>s on which
     *            {@link Object#toString()} will be called
     * @return the concatenation of String representations of the objects in
     *         the list
     */
    public static String join(String toJoin, Object[] list) {
        if (list == null || list.length == 0)
            return "";
        StringBuilder builder = new StringBuilder();
        String delimiter = nonNull(toJoin);
        int i = 0;
        for (; i < (list.length - 1); i++) {
            if (list[i] != null)
                builder.append(list[i]);
            builder.append(delimiter);
        }
        builder.append(list[i]);
        return builder.toString();
    }

    /**
     * An equivalent of Python's <code>str.join()</code> function on lists: it
     * returns a String which is the concatenation of the strings in the
     * argument list. The separator between elements is the string providing
     * this method. The separator is only inserted between elements: there's
     * no separator before the first element or after the last.
     *
     * @param toJoin
     *            the separator, if <code>null</code> the empty String is used
     * @param list
     *            a list of <code>Object</code>s on which
     *            {@link Object#toString()} will be called
     * @return the concatenation of String representations of the objects in
     *         the list
     */
    public static String join(String toJoin, List list) {
        if (list == null || list.isEmpty())
            return "";
        StringBuilder builder = new StringBuilder();
        String delimiter = nonNull(toJoin);
        int i = 0;
        for (; i < list.size() - 1; i++) {
            if (list.get(i) != null)
                builder.append(list.get(i));
            builder.append(delimiter);
        }
        builder.append(list.get(i));
        return builder.toString();
    }

    /**
     * An equivalent of Python's <code>str.join()</code> function on lists: it
     * returns a String which is the concatenation of the strings in the
     * argument list. The separator between elements is the string providing
     * this method. The separator is only inserted between elements: there's
     * no separator before the first element or after the last.
     *
     * @param toJoin
     *            the separator, if <code>null</code> the empty String is used
     * @param set
     *            a set of <code>Object</code>s on which
     *            {@link Object#toString()} will be called
     * @return the concatenation of String representations of the objects in
     *         the set
     */
    public static String join(String toJoin, Set set) {
        return join(toJoin, set.toArray());
    }
    /**
     * Checks whether the argument <tt>array</tt> contains at least a
     * <code>null</code> value.
     *
     * @param array
     *            the array to be checked.
     * @return <code>true</code> in case <em>at least</em> one of the values
     *         stored in the argument <tt>array</tt> is <code>null</code>, or
     *         in case the <tt>array</tt> itself is <code>null</code>.
     */
    public static boolean containsNull(Object[] array) {
        if (array == null)
            return true;
        for (Object o : array) {
            if (o == null)
                return true;
        }
        return false;
    }

    /**
     * Checks whether the argument <tt>list</tt> contains at least a
     * <code>null</code> value.
     *
     * @param list
     *            the list to be checked
     * @return <code>true</code> in case <em>at least</em> one of the values
     *         stored in the argument <tt>array</tt> is <code>null</code>, or
     *         in case the <tt>list</tt> itself is <code>null</code>
     */
    public static boolean containsNull(List list) {
        if (list == null)
            return true;
        for (Object o : list) {
            if (o == null)
                return true;
        }
        return false;
    }

    /**
     * Checks whether the argument <tt>string</tt> is <code>null</code> or
     * empty. Please note that the <tt>string</tt> is
     * <strong>trimmed</strong>, so that a check on a string containing
     * white spaces only will always return <code>true</code>.
     *
     * @param string
     *            the string to be checked
     * @return <code>true</code> in case the argument <tt>string</tt> is
     *         <code>null</code>, empty ({@link String#length()} returns 0) or
     *         contains only white spaces (
     *         <tt>{@link String#trim()}.length()</tt> returns 0)
     */
    public static boolean isNullOrEmpty(String string) {
        return string == null || string.trim().length() == 0;
    }
}

I don’t know what’s wrong with the syntax highlighter… here’s the same class in pastebin!

Advertisements

3 thoughts on “Some simple utility methods I use a lot in Java

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s