📜  如何在Java Map 中找到具有最大值的条目

📅  最后修改于: 2022-05-13 01:54:42.869000             🧑  作者: Mango

如何在Java Map 中找到具有最大值的条目

给定Java中的地图,任务是找出该地图中具有最高值的条目。

插图:

Input  : Map = {ABC = 10, DEF = 30, XYZ = 20}
Output : DEF = 30
Input  : Map = {1 = 40, 2 = 30, 3 = 60}
Output : 3 = 60

方法:可以有几种方法来实现以下列出的目标:  

  1. 通过for每个循环的简单迭代方法
  2. 使用 Collections 类中的 max() 方法
  3. 使用Java 8 中引入的 Streams 概念

现在我们将与过程一起讨论上面提出的方法,并通过干净的Java程序来实现它们。

方法1:对每个循环使用迭代方法

方法:

  1. 逐个迭代映射条目
  2. 将第一个条目存储在参考变量中以进行初始比较。
  3. 如果当前条目的值大于引用条目的值,则将当前条目存储为引用条目。
  4. 对地图中的所有条目重复此过程。
  5. 最后,引用变量具有映射中最高值的所需条目。
  6. 打印此条目
for (Map.Entry entry : map.entrySet()) 
{ // Operations }

例子:

Java
// Java program to Find Entry
// with the Highest Value in Map
// Using Comparators in Map interface
 
// Importing all utility classes
import java.util.*;
 
// Main class
class GFG {
 
    // Method 1
    // Find the entry with highest value
    public static  >
        Map.Entry
        getMaxEntryInMapBasedOnValue(Map map)
    {
 
        // To store the result
        Map.Entry entryWithMaxValue = null;
 
        // Iterate in the map to find the required entry
        for (Map.Entry currentEntry :
             map.entrySet()) {
 
            if (
                // If this is the first entry, set result as
                // this
                entryWithMaxValue == null
 
                // If this entry's value is more than the
                // max value Set this entry as the max
                || currentEntry.getValue().compareTo(
                       entryWithMaxValue.getValue())
                       > 0) {
 
                entryWithMaxValue = currentEntry;
            }
        }
 
        // Return the entry with highest value
        return entryWithMaxValue;
    }
 
    // Method 2
    // To print the map
    public static void print(Map map)
    {
 
        System.out.print("Map: ");
 
        // If map does not contain any value
        if (map.isEmpty()) {
 
            System.out.println("[]");
        }
        else {
            System.out.println(map);
        }
    }
 
    // Method 3
    // Main driver method
    public static void main(String[] args)
    {
 
        // Creating a Map
        // Declaring object of string and integer type
        Map map = new HashMap<>();
 
        // Inserting elements in the Map object
        // using put() method
        // Custom input element addition
        map.put("ABC", 10);
        map.put("DEF", 30);
        map.put("XYZ", 20);
 
        // Calling method 2 to
        // print the map
        print(map);
 
        // Calling method 1 to
        // find the entry with highest value and
        // print on the console
        System.out.println(
            "Entry with highest value: "
            + getMaxEntryInMapBasedOnValue(map));
    }
}


Java
// Java Program to Find Entry with largest Value in Map
// Using max() method from Collections class
 
// Importing required classes
import java.util.*;
 
// main class
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Creating HashMap
        // Declaring objects of string and integer type
        HashMap map
            = new HashMap();
 
        // Inserting elements in the Map
        // using put() method
 
        // Custom input addition
        map.put(1, 4);
        map.put(2, 5);
        map.put(3, 7);
        map.put(4, 2);
 
        // Using Collections.max() method returning max
        // value in HashMap and storing in a integer
        // variable
        int maxValueInMap = (Collections.max(map.values()));
 
        // Iterate through HashMap
        for (Entry entry :
             map.entrySet()) {
 
            if (entry.getValue() == maxValueInMap) {
 
                // Print the key with max value
                System.out.println(entry.getKey());
            }
        }
    }
}


Java
// Java Program to Find Entry with largest Value in Map
// Using concept of Streams
import java.util.stream.*;
 
// Main class
class GFG {
 
    // Method 1
    public static void main(String[] args)
    {
 
        // Entries in our map
        Map map = new HashMap<>();
 
        map.put("A", "23");
        map.put("F", "43");
        map.put("C", "56");
        map.put("Z", "04");
 
        // Printing the largest value in map by
        // calling above method
        System.out.print(map.maxUsingStreamAndLambda());
    }
 
    // Method 2
    public 
        extends Comparable > maxUsingStreamAndLambda(
                    Map map)
    {
 
        // Using lambda operation over streams
        Map maxEntry
            = map.entrySet().stream().max(
                (String e1, String e2)
                    -> e1.getValue().compareTo(
                        0e2.getValue()));
 
        // Returning the maximum element from map
        return maxEntry.get().getValue();
    }
}


输出:
Map: {ABC=10, DEF=30, XYZ=20}
Entry with highest value: DEF=30

方法 2:在没有 lambda 表达式的情况下使用 Collections 类中的 max() 方法

例子:

Java

// Java Program to Find Entry with largest Value in Map
// Using max() method from Collections class
 
// Importing required classes
import java.util.*;
 
// main class
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Creating HashMap
        // Declaring objects of string and integer type
        HashMap map
            = new HashMap();
 
        // Inserting elements in the Map
        // using put() method
 
        // Custom input addition
        map.put(1, 4);
        map.put(2, 5);
        map.put(3, 7);
        map.put(4, 2);
 
        // Using Collections.max() method returning max
        // value in HashMap and storing in a integer
        // variable
        int maxValueInMap = (Collections.max(map.values()));
 
        // Iterate through HashMap
        for (Entry entry :
             map.entrySet()) {
 
            if (entry.getValue() == maxValueInMap) {
 
                // Print the key with max value
                System.out.println(entry.getKey());
            }
        }
    }
}

输出:

3

方法3:使用Java 8中引入的Streams的概念

Java

// Java Program to Find Entry with largest Value in Map
// Using concept of Streams
import java.util.stream.*;
 
// Main class
class GFG {
 
    // Method 1
    public static void main(String[] args)
    {
 
        // Entries in our map
        Map map = new HashMap<>();
 
        map.put("A", "23");
        map.put("F", "43");
        map.put("C", "56");
        map.put("Z", "04");
 
        // Printing the largest value in map by
        // calling above method
        System.out.print(map.maxUsingStreamAndLambda());
    }
 
    // Method 2
    public 
        extends Comparable > maxUsingStreamAndLambda(
                    Map map)
    {
 
        // Using lambda operation over streams
        Map maxEntry
            = map.entrySet().stream().max(
                (String e1, String e2)
                    -> e1.getValue().compareTo(
                        0e2.getValue()));
 
        // Returning the maximum element from map
        return maxEntry.get().getValue();
    }
}

输出:

C