简体   繁体   English

如何遍历数组并找到最大值:Java

[英]How to iterate through array and find highest value: Java

In the Bellow code I am supposed to find the month that correlates with the largest number.在 Bellow 代码中,我应该找到与最大数字相关的月份。

Bellow is what I tried.波纹管是我试过的。 However I belive that there is likly a more consice way to write this.但是我相信有一种更简洁的方式来写这个。 How can I make it that way?我怎样才能做到这一点?

public class HelloWorld{

static int[] array = {3,6,7,3,2,30,9,13,12,1,2,1};
static String[] month = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};

static int greatestVal = 0;
static int greatestVal2 = 0;
static String monthChosen = "";

int integer = 0;
static int num = 0;

     public static void main(String []args){
            int number = -1;
            for (int i = 0; i<=11; i++) {
                int currentValue = array[i];
                number += 1;
                //System.out.println(currentValue);
                for (int index = 0; index <=11; index++) {
                    if (currentValue > array[index]) {
                        greatestVal = currentValue;
                        // System.out.println(currentValue +">"+ array[index]);
                        if (greatestVal > greatestVal2) {
                            greatestVal2 = greatestVal;
                            monthChosen = month[number];
                        }
                    } else {
                        // System.out.print("Hgfhdssdgfadkhfdshkjhads");
                    }
                }
        }
            System.out.println(greatestVal2 + " greatest month is: " + monthChosen);
    }
}

With streams:使用流:

static int[] array = {3,6,7,3,2,30,9,13,12,1,2,1};
static String[] month = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};

public static void main(String[] args) {
    int index = IntStream.range(0, array.length)
            .reduce(0, (a, b) -> array[a] >= array[b] ? a : b);
    System.out.println(array[index] + " greatest month is: " + month[index]);
}

You don't actually need to keep track of the chosen month for every iteration.您实际上并不需要为每次迭代跟踪所选月份。 Assuming months are related to the array elements by the index, all you need is to find out the index of the greatest element - you don't even need to track the greatest value:假设月份通过索引与数组元素相关,您只需要找出最大元素的索引 - 您甚至不需要跟踪最大值:

public class HelloWorld {
    static int[] array = {3, 6, 7, 3, 2, 30, 9, 13, 12, 1, 2, 1};
    static String[] month = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};

    public static void main(String[] args) {
        int index = 0;
        for (int i = 1; i < array.length; i++)
            if (array[index] < array[i])
                index = i;
        System.out.println(array[index] + " greatest month is: " + month[index]);
    }
}

if you can use a Map then its very straight forward.如果您可以使用Map那么它非常简单。 Create a HashMap<String, Integer> where the key is the month and value is the count.创建一个HashMap<String, Integer> ,其中key是月份, value是计数。

You can then iterate over this map and find the key, value pair for which the value is the largest.然后,您可以遍历此映射并找到值最大的键值对。

Solution :解决方案 :

    Map<String, Integer> monthMap = new HashMap<>();
    // initializing the map
    for (int i = 0; i < 12; i++)
        monthMap.put(month[i], array[i]);

    // finding <k, v> pair with highest entry
    Entry<String, Integer> entry = monthMap.entrySet().stream()
             .max(Map.Entry.comparingByValue(Comparator.comparingInt(i -> i.intValue())))
             .get();

Simplified solution just using your 2 arrays...仅使用您的 2 个阵列的简化解决方案...

    int max = Arrays.stream(array).max().getAsInt();
    int index = 0;
    for (int i = 0; i < array.length; i++) {
        if (array[i] == max) {
            index = i;
        }
    }
    System.out.println(array[index] + " greatest month is: " + month[index]);
   public static void main(String []args){
        Integer[] array = {3,6,7,3,2,30,9,13,12,1,2,1};
        String[] month = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};

        Integer[] copyArr = array.clone();
        Arrays.sort(copyArr);
        int largestNum = copyArr[copyArr.length-1];
        int index = Arrays.binarySearch(array, largestNum);
        System.out.println(month[index]);
     }

output -> June输出 -> 六月

In Java we have enums where you can have your Constants and the values associated with it.在 Java 中,我们有枚举,您可以在其中拥有常量和与之关联的值。 Refer https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html参考https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html

Using the approach you may define an enum where name would be month and values can be associated with them.使用该方法,您可以定义一个枚举,其中名称为月份,值可以与它们相关联。

Now in any other method you can go ahead iterate over the enum values and then find the maximum value.现在在任何其他方法中,您可以继续迭代枚举值,然后找到最大值。 So assume Months is the name of the enum then you can use a simple for-each loop for this:因此,假设 Months 是枚举的名称,那么您可以for-each使用一个简单的for-each循环:

for (Months months:Months.values()){
  //logic for comparison.find the maximum
}

Note : ENUMS are generally used for constants.So not sure if the described problem is always going to have constant values for each month or it can vary.If it varies then you can go with streams or Maps as described in already given answers.注意:ENUMS 通常用于常量。所以不确定所描述的问题是否总是每个月都有常量值,或者它可能会有所不同。如果它有所不同,那么您可以按照已经给出的答案中的描述使用streamsMaps

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM