查找与Java Map中的最大值关联的密钥

时间:2011-05-06 12:07:31

标签: java hashmap

获取地图中最大值关键字的最简单方法是什么?

我相信当您需要与最大值对应的键时,Collections.max(someMap)将返回最大键。

18 个答案:

答案 0 :(得分:115)

基本上你需要遍历地图的入口集,记住“当前已知的最大值”和与之关联的密钥。 (或者只是包含两者的条目。)

例如:

Map.Entry<Foo, Bar> maxEntry = null;

for (Map.Entry<Foo, Bar> entry : map.entrySet())
{
    if (maxEntry == null || entry.getValue().compareTo(maxEntry.getValue()) > 0)
    {
        maxEntry = entry;
    }
}

答案 1 :(得分:86)

为了完整起见,这是一种方式

countMap.entrySet().stream().max((entry1, entry2) -> entry1.getValue() > entry2.getValue() ? 1 : -1).get().getKey();

Collections.max(countMap.entrySet(), (entry1, entry2) -> entry1.getValue() - entry2.getValue()).getKey();

Collections.max(countMap.entrySet(), Comparator.comparingInt(Map.Entry::getValue)).getKey();

答案 2 :(得分:46)

此代码将打印所有具有最大值的键

public class NewClass4 {
    public static void main(String[] args)
    {
        HashMap<Integer,Integer>map=new HashMap<Integer, Integer>();
        map.put(1, 50);
        map.put(2, 60);
        map.put(3, 30);
        map.put(4, 60);
        map.put(5, 60);
        int maxValueInMap=(Collections.max(map.values()));  // This will return max value in the Hashmap
        for (Entry<Integer, Integer> entry : map.entrySet()) {  // Itrate through hashmap
            if (entry.getValue()==maxValueInMap) {
                System.out.println(entry.getKey());     // Print the key with max value
            }
        }

    }
}

答案 3 :(得分:36)

使用Java-8的简单单行程序

Key key = Collections.max(map.entrySet(), Map.Entry.comparingByValue()).getKey();

答案 4 :(得分:8)

通过定义适当的Comparator,这是如何直接做到的(没有明确的额外循环):

int keyOfMaxValue = Collections.max(
                        yourMap.entrySet(), 
                        new Comparator<Entry<Double,Integer>>(){
                            @Override
                            public int compare(Entry<Integer, Integer> o1, Entry<Integer, Integer> o2) {
                                return o1.getValue() > o2.getValue()? 1:-1;
                            }
                        }).getKey();

答案 5 :(得分:5)

答案返回一个Optional,因为如果地图为空,则该地图可能没有最大值: map.entrySet().stream().max(Map.Entry.comparingByValue()).map(Map.Entry::getKey);

答案 6 :(得分:4)

Java 8获取最大值的所有键的方法。

Integer max = PROVIDED_MAP.entrySet()
            .stream()
            .max((entry1, entry2) -> entry1.getValue() > entry2.getValue() ? 1 : -1)
            .get()
            .getValue();

List listOfMax = PROVIDED_MAP.entrySet()
            .stream()
            .filter(entry -> entry.getValue() == max)
            .map(Map.Entry::getKey)
            .collect(Collectors.toList());

System.out.println(listOfMax);

您也可以使用parallelStream()代替stream()

对其进行并行化

答案 7 :(得分:4)

我有两种方法,使用这个方法来获取具有最大值的键:

 public static Entry<String, Integer> getMaxEntry(Map<String, Integer> map){        
    Entry<String, Integer> maxEntry = null;
    Integer max = Collections.max(map.values());

    for(Entry<String, Integer> entry : map.entrySet()) {
        Integer value = entry.getValue();
        if(null != value && max == value) {
            maxEntry = entry;
        }
    }
    return maxEntry;
}

例如,使用以下方法获取具有最大值的条目:

  Map.Entry<String, Integer> maxEntry =  getMaxEntry(map);

使用 Java 8 ,我们可以得到一个包含最大值的对象:

Object maxEntry = Collections.max(map.entrySet(), Map.Entry.comparingByValue()).getKey();      

System.out.println("maxEntry = " + maxEntry);

答案 8 :(得分:3)

1。使用流

public <K, V extends Comparable<V>> V maxUsingStreamAndLambda(Map<K, V> map) {
    Optional<Entry<K, V>> maxEntry = map.entrySet()
        .stream()
        .max((Entry<K, V> e1, Entry<K, V> e2) -> e1.getValue()
            .compareTo(e2.getValue())
        );

    return maxEntry.get().getKey();
}

2。在Lambda表达式中使用Collections.max()

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

3。结合使用流和方法参考

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

4。使用Collections.max()

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

5。使用简单迭代

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

答案 9 :(得分:2)

此解决方案可以吗?

int[] a = { 1, 2, 3, 4, 5, 6, 7, 7, 7, 7 };
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i : a) {
Integer count = map.get(i);
map.put(i, count != null ? count + 1 : 0);
}
Integer max = Collections.max(map.keySet());
System.out.println(max);
System.out.println(map);

答案 10 :(得分:0)

对于我的项目,我使用了Jon和Fathah解决方案的略微修改版本。如果多个条目具有相同的值,则返回它找到的最后一个条目:

public static Entry<String, Integer> getMaxEntry(Map<String, Integer> map) {        
    Entry<String, Integer> maxEntry = null;
    Integer max = Collections.max(map.values());

    for(Entry<String, Integer> entry : map.entrySet()) {
        Integer value = entry.getValue();

        if(null != value && max == value) {
            maxEntry = entry;
        }
    }

    return maxEntry;
}

答案 11 :(得分:0)

int maxValue = 0;
int mKey = 0;
for(Integer key: map.keySet()){
    if(map.get(key) > maxValue){
        maxValue = map.get(key);
        mKey = key;
    }
}
System.out.println("Max Value " + maxValue + " is associated with " + mKey + " key");

答案 12 :(得分:0)

地图中的多数元素/最大元素:

public class Main {
     public static void main(String[] args) {
     int[] a = {1,3,4,3,4,3,2,3,3,3,3,3};
     List<Integer> list = Arrays.stream(a).boxed().collect(Collectors.toList());
     Map<Integer, Long> map = list.parallelStream()
             .collect(Collectors.groupingBy(Function.identity(),Collectors.counting()));
     System.out.println("Map => " + map);
     //{1=1, 2=1, 3=8, 4=2}
     map.entrySet()
     .stream()
     .max(Comparator.comparing(Entry::getValue))//compare the values and get the maximum value
     .map(Entry::getKey)// get the key appearing maximum number of times
     .ifPresentOrElse(System.out::println,() -> new RuntimeException("no such thing"));

     /*
      * OUTPUT : Map => {1=1, 2=1, 3=8, 4=2} 
      * 3
      */
     // or in  this way 
     System.out.println(".............");
     Integer maxAppearedElement = map.entrySet()
             .parallelStream()
             .max(Comparator.comparing(Entry::getValue))
             .map(Entry::getKey)
             .get();
     System.out.println(maxAppearedElement);

     } 
}

答案 13 :(得分:0)

给定的地图

HashMap abc =新的HashMap <>();

获取所有具有最大值的地图条目。

您可以在过滤器中使用以下任何一种方法来获取一组对应的最小值或最大值的映射条目

Collections.max(abc.values())
Collections.min(abc.values())
Collections.max(abc.keys())
Collections.max(abc.keys())

abc.entrySet().stream().filter(entry -> entry.getValue() == Collections.max(abc.values()))

如果只想获取过滤器映射的键

abc.entrySet()
       .stream()
       .filter(entry -> entry.getValue() == Collections.max(abc.values()))
       .map(Map.Entry::getKey);

如果要获取过滤后的地图的值

abc.entrySet()
      .stream()
      .filter(entry -> entry.getValue() == Collections.max(abc.values()))
      .map(Map.Entry::getvalue)

如果要在列表中获取所有此类密钥:

abc.entrySet()
  .stream()
  .filter(entry -> entry.getValue() == Collections.max(abc.values()))
  .map(Map.Entry::getKey)
  .collect(Collectors.toList())

如果要在列表中获取所有此类值:

abc.entrySet()
  .stream()
  .filter(entry -> entry.getValue() == Collections.max(abc.values()))
  .map(Map.Entry::getvalue)
  .collect(Collectors.toList())

答案 14 :(得分:0)

简单易懂。 在下面的代码中,maxKey是保持最大值的键。

int maxKey = 0;
int maxValue = 0;
for(int i : birds.keySet())
{
    if(birds.get(i) > maxValue)
    {
        maxKey = i;
        maxValue = birds.get(i);
    }
}

答案 15 :(得分:0)

这将返回 Map<Integer, Integer> 中具有最大值的键

public Set<Integer> getMaxKeys(Map<Integer, Integer> map) { 

        if (map.isEmpty()) {
            return Collections.emptySet();
        }

        return map
        .entrySet()
        .stream()
        .collect(
            groupingBy(
                Map.Entry::getValue, TreeMap::new, mapping(Map.Entry::getKey, toSet())
            )
         )
         .lastEntry()
         .getValue();
    }

答案 16 :(得分:0)

最简单的方法是:

Collections.max(hmap.values());

答案 17 :(得分:-2)

你可以这样做

SELECT tb1.*, tb2.*
   FROM takensubject tb2
   INNER JOIN student tb1
   ON tb1.S_ID= tb2.S_ID
   WHERE SchoolYear ='$Sy' 
   and Semester ='$Sem' 
   and SubjectCode='$sescode' and Time='$sestime';