Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
//License from project: Open Source License 

import java.util.Map;

public class Main {
    /**
     * Returns the object in the {@link Map} specified by its key. If it doesn't
     * exist, returns its default value.
     * 
     * @param map
     *            - The map containing the elements to inspect.
     * @param key
     *            - The key of the value to return.
     * @param defaultValue
     *            - The default value to return in case the key doesn't match a
     *            value in the map.
     * @return The value mapped to the specified key, or the default value.
     */
    @SuppressWarnings("unchecked")
    public static <T> T getMapValue(Map<?, ?> map, Object key, T defaultValue) {
        if (!map.containsKey(key)) {
            return defaultValue;
        } else {
            return (T) map.get(key);
        }
    }

    /**
     * Returns the first object in the {@link Map} whose key <b>is represented
     * by or starts with some of the characters of the specified seed</b>. This
     * method allows developers to simulate a reverse {@code startsWith}
     * operation in a {@code Map}. That is, the map key only contains some of
     * the initial characters in the seed.
     * <p>
     * If the map contains a complete key represented by the {@code seed}
     * parameter, such a value will be returned. Otherwise, the method will go
     * trough all the map entries looking for the first key whose characters
     * match the specified seed. If none of the keys match the seed in any way,
     * the default value will be returned. For example:
     * 
     * <pre>
     * String seed = "prefix_mapentry";
     * Map<String, String> map = new HashMap<>();
     * 
     * map.put("first.key", "1");
     * map.put("prefix_", "2");
     * map.put("third.key", "3");
     * 
     * System.out.println(getMapValue(map, seed, null));
     * </pre>
     * 
     * The following value will be printed:
     * 
     * <pre>
     * 2
     * </pre>
     * 
     * @param map
     *            - The map containing the elements to inspect.
     * @param seed
     *            - The key of the value to return.
     * @param defaultValue
     *            - The default value to return in case the key doesn't match an
     *            entry in the map.
     * @return The value mapped to the specified key, or the default value.
     */
    public static <T> T getMapValue(final Map<String, T> map, final String seed, T defaultValue) {
        if (map.containsKey(seed)) {
            return map.get(seed);
        } else {
            for (Map.Entry<String, T> entry : map.entrySet()) {
                if (seed.startsWith(entry.getKey())) {
                    return entry.getValue();
                }
            }
        }
        return defaultValue;
    }
}