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.Arrays;
import java.util.Collection;

import java.util.Hashtable;

import java.util.Map;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collectors;

public class Main {
    /**
     * Convert a collection to Hashtable. The key is decided by keyMapper, value
     * is the object in collection
     * 
     * @param entities
     * @param keyMapper
     * @return
     */
    public static <T, K> Hashtable<K, T> toHashtable(Collection<T> entities, Function<T, K> keyMapper) {
        return toMap(entities, keyMapper, Hashtable<K, T>::new);
    }

    public static <T, K> Hashtable<K, T> toHashtable(T[] entities, Function<T, K> keyMapper) {
        return toHashtable(Arrays.asList(entities), keyMapper);
    }

    public static <T, K, V> Hashtable<K, V> toHashtable(Collection<T> entities, Function<T, K> keyMapper,
            Function<T, V> valueMapper) {
        return toMap(entities, keyMapper, valueMapper, Hashtable<K, V>::new);
    }

    public static <T, K, V> Hashtable<K, V> toHashtable(T[] entities, Function<T, K> keyMapper,
            Function<T, V> valueMapper) {
        return toHashtable(Arrays.asList(entities), keyMapper, valueMapper);
    }

    public static <T, K, M extends Map<K, T>> M toMap(Collection<T> entities, Function<T, K> keyMapper,
            Supplier<M> supplier) {
        return entities.stream().collect(Collectors.toMap(keyMapper, Function.identity(), (a, b) -> b, supplier));
    }

    public static <T, K, V, M extends Map<K, V>> M toMap(Collection<T> entities, Function<T, K> keyMapper,
            Function<T, V> valueMapper, Supplier<M> supplier) {
        return entities.stream().collect(Collectors.toMap(keyMapper, valueMapper, (a, b) -> b, supplier));
    }
}