Java 集合-取最大/最小值

104 篇文章 0 订阅
32 篇文章 0 订阅

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);
	}

}

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

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值