Java集合提取眾數

之前有個需求在解決,然後需要用到眾數,網上找來許多demo都沒辦法解決需求,最後自己琢磨出一個。

(1)先說下我的思路吧,把需要求眾數的值全部丟到一個數組或者集合裡,然後匹配出每個值所出現的次數,將值作為HashMap的Key,出現的次數作為Value。再者通過最大的Value去查找對應Key。
運行結果將得到一個集合!

import java.util.*;

/**
 * @Author Joshua_Zheng
 * @WritingTime 2018/6/19
 * @Describe 提取眾數
 **/
public class TestPriority {
    static Random random = new Random();

    public static void main(String[] args) {
        List JumpTimes = new ArrayList();
        for (int i = 0; i < 8; i++) {
            JumpTimes.add(random.nextInt(6) + 1);
        }
        System.err.println(JumpTimes);
        System.err.println(getUnity(JumpTimes));
    }

/---------------------------邏輯代碼塊--------------------------------------------/
    // 獲取眾數
    public static List<Integer> getUnity(List jumpTimes) {
        Map<Integer, Integer> map = new HashMap();
        for (int i = 0; i < jumpTimes.size(); i++) {
            if (map.get(jumpTimes.get(i)) == null) {
                map.put((Integer) jumpTimes.get(i), 1);
            } else {
                int num = map.get(jumpTimes.get(i));
                map.put((Integer) jumpTimes.get(i), num + 1);
            }
        }
		//System.err.println(map);
        List<Integer> unitys = new ArrayList<>();
        //獲取最大的Value
        Collection<Integer> c = map.values();
        Object[] obj = c.toArray();
        Arrays.sort(obj);
        //根據Value獲取對應的Key
        for (Object key : map.keySet()) {
            if (map.get(key).equals(obj[obj.length - 1])) {
                unitys.add((Integer) key);
            }
        }
        return unitys;
    }
}

單個眾數時
在这里插入图片描述

多個眾數時
在这里插入图片描述

如果各位大佬有更好的解決方案,希望提出

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值