Java List Min min(List a, List b)

Here you can find the source of min(List a, List b)

Description

min

License

Open Source License

Parameter

Parameter Description
T a parameter
a a parameter
b a parameter

Declaration

@SuppressWarnings("unchecked")
public static <T> List<T> min(List<? extends T> a, List<? extends T> b) 

Method Source Code


//package com.java2s;
/* License as published by the Free Software Foundation; either         */

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Main {
    /**//  ww  w .  j  av a 2 s .com
     * @param <T>
     * @param a
     * @param b
     * @return
     */
    @SuppressWarnings("unchecked")
    public static <T> List<T> min(List<? extends T> a, List<? extends T> b) {
        if (a == null)
            return (List<T>) b;
        if (b == null)
            return (List<T>) a;
        List<T> result = new ArrayList<T>();
        if (a.isEmpty() || b.isEmpty())
            return result;
        Map<T, Integer> coeffs = new HashMap<T, Integer>();
        buildMap(a, coeffs);
        for (T t : b) {
            Integer coeff = coeffs.remove(t);
            if (coeff != null) {
                int newCoeff = coeff - 1;
                if (newCoeff > 0) {
                    coeffs.put(t, newCoeff);
                    result.add(t);
                }
            }
        }
        return result;
    }

    private static <T> void buildMap(List<? extends T> a, Map<T, Integer> coeffs) {
        for (T t : a) {
            Integer coeff = coeffs.get(t);
            if (coeff == null) {
                coeffs.put(t, 1);
            } else {
                coeffs.put(t, coeff + 1);
            }
        }
    }
}

Related

  1. getMinimums(List data)
  2. getMinValue(List values)
  3. getMinWhitespace(final List lines)
  4. min(final List aList, final Double aDefalut)
  5. min(List values)
  6. min(List booleans)
  7. min(List data)
  8. min(List l)
  9. min(List list)