Java 集合-取最大/最小值

Java 集合-取最大/最小值

List、Map集合取最大最小值可以简单借用collection中的max和min方法。
min的源码

public static <T extends Object & Comparable<? super T>> T min(Collection<? extends T> coll) {
        Iterator<? extends T> i = coll.iterator();
        T candidate = i.next();

        while (i.hasNext()) {
            T next = i.next();
            if (next.compareTo(candidate) < 0)
                candidate = next;
        }
        return candidate;
    }

max的源码

public static <T extends Object & Comparable<? super T>> T max(Collection<? extends T> coll) {
        Iterator<? extends T> i = coll.iterator();
        T candidate = i.next();

        while (i.hasNext()) {
            T next = i.next();
            if (next.compareTo(candidate) > 0)
                candidate = next;
        }
        return candidate;
    }

Java 集合list取最大值和最小值

代码

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Collection {

	public static void ListMaxMin(List<Integer> listA) {
		System.out.println("listA --- " + listA.toString());
		System.out.println("max = " + Collections.max(listA));
		System.out.println("min = " + Collections.min(listA));
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		List<Integer> list = new ArrayList<Integer>();
		for (int i = 0; i < 10; i++) {
			int a = (int) (Math.random() * 30 + 1);
			list.add(a);
		}
		ListMaxMin(list);

	}

}

测试输出
在这里插入图片描述

Java 集合map取最大值和最小值

代码


public class Collection {
	
	public static void MapMaxMin(Map<String,Integer> mapA) {
		Collection<Integer> map =mapA.values();
		Integer max = Collections.max(map);
		Integer min = Collections.min(map);
		System.out.println("mapA --- " + mapA.toString());
		System.out.println("max = " + max);
		System.out.println("min = " + min);
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Map<String,Integer> map = new HashMap<String, Integer>();
		for (int i = 0; i < 10; i++) {
			int a = (int) (Math.random() * 30 + 1);
			map.put(i+"", a);
		}
	
		System.out.println("--------------");
		System.out.println();
		MapMaxMin(map);
	}

}

测试输出
在这里插入图片描述


版权声明:本文为weixin_43421142原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。