Find the Biggest number in HashSet/HashMap java

后端 未结 8 2169
我在风中等你
我在风中等你 2020-12-29 04:48

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 Ha

8条回答
  •  天涯浪人
    2020-12-29 05:04

    Note : If you want to find the biggest value from Map try maxEntry.get().getValue() instead of maxEntry.get().getKey()

    1. Using Stream

    public > V maxUsingStreamAndLambda(Map map) {
        Optional> maxEntry = map.entrySet()
            .stream()
            .max((Entry e1, Entry e2) -> e1.getValue()
                .compareTo(e2.getValue())
            );
    
        return maxEntry.get().getKey();
    }
    

    2. Using Collections.max() with a Lambda Expression

    public > V maxUsingCollectionsMaxAndLambda(Map map) {
        Entry maxEntry = Collections.max(map.entrySet(), (Entry e1, Entry e2) -> e1.getValue()
            .compareTo(e2.getValue()));
        return maxEntry.getKey();
    }
    

    3. Using Stream with Method Reference

    public > V maxUsingStreamAndMethodReference(Map map) {
        Optional> maxEntry = map.entrySet()
            .stream()
            .max(Comparator.comparing(Map.Entry::getValue));
        return maxEntry.get()
            .getKey();
    }
    

    4. Using Collections.max()

    public > V maxUsingCollectionsMax(Map map) {
        Entry maxEntry = Collections.max(map.entrySet(), new Comparator>() {
            public int compare(Entry e1, Entry e2) {
                return e1.getValue()
                    .compareTo(e2.getValue());
            }
        });
        return maxEntry.getKey();
    }
    

    5. Using Simple Iteration

    public > V maxUsingIteration(Map map) {
        Map.Entry maxEntry = null;
        for (Map.Entry entry : map.entrySet()) {
            if (maxEntry == null || entry.getValue()
                .compareTo(maxEntry.getValue()) > 0) {
                maxEntry = entry;
            }
        }
        return maxEntry.getKey();
    }
    

提交回复
热议问题