Find the Biggest number in HashSet/HashMap java

2020-02-23 06:32发布

I would like to find the biggest number in HashSet and HashMap. Say I have the number [22,6763,32,42,33] in my HashSet and I want to find the largest number in my current HashSet..how would i do this? and Same thing for the HashMap as well. I hope you can help me with it. Thank you.

8条回答
贪生不怕死
2楼-- · 2020-02-23 06:58

Consider using Apache Commons Math. Here is the API docs.
The class of interest is SummaryStatistics. It works with doubles and computes max, min, mean etc. on the fly (as you add values to it). The data values are not stored in memory, so this class can be used to compute statistics for very large data streams.

查看更多
虎瘦雄心在
3楼-- · 2020-02-23 06:59

Something like this:

Set<Integer> values = new HashSet<Integer>() {{
    add(22);
    add(6763);
    add(32);
    add(42);
    add(33);
}};
int maxValue = Integer.MIN_VALUE;
for (int value : values) {
    if (value > maxValue) {
        maxValue = value;
    }
}

And this:

Map<String, Integer> values = new HashMap<String, Integer>() {{
    put("0", 22);
    put("1", 6763);
    put("2", 32);
    put("3", 42);
    put("4", 33);
}};
int maxValue = Integer.MIN_VALUE;
for (int value : values.values()) {
    if (value > maxValue) {
        maxValue = value;
    }
}
查看更多
登录 后发表回答