Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
import java.lang.reflect.Method;
import java.util.ArrayList;

import java.util.List;

public class Main {
    /**
     * Creates a list of values extracted from the provided list using the
     * specified value method, keeping the order of the provided list.
     */
    @SuppressWarnings("unchecked")
    public static <K, T> List<K> createList(List<T> list, String valueMethod) {
        List<K> valueList = new ArrayList<>(list.size());

        if (list.isEmpty()) {
            return valueList;
        }

        Class<?> elementClass = list.iterator().next().getClass();

        Method getValueMethod;

        try {
            getValueMethod = elementClass.getMethod(valueMethod, new Class[0]);
        } catch (Exception e) {
            throw new RuntimeException("Failed to get key method", e);
        }

        for (T element : list) {
            K value;

            try {
                value = (K) getValueMethod.invoke(element, (Object[]) null);
            } catch (Exception e) {
                throw new RuntimeException("Failed to get key", e);
            }

            valueList.add(value);
        }

        return valueList;
    }
}