繁体   English   中英

如何在 Java 中的 Int、float 和 String 数组中找到最大值和最小值

[英]How to find Maximum and Minimum in an array of Int,float and String in Java

有没有办法找出由整数、浮点数和字符串或字符组成的数组的最大值和最小值? 在 Java 中

例如:A={1,2,3,4,4.5,4.4,NA,NA,NA}

所以忽略所有的字符和字符串

预期结果:此处最大元素为 4.5,最小元素为 1

这应该有望完成工作。 我只考虑过 int、double 和 string。

    ArrayList<Object> list = new ArrayList<Object>(Arrays.asList(1, 2, 3, 4, 4.5, 4.4, "NA", "NA", "NA"));
    double num , max  = Float.MIN_VALUE;
    for (Object item : list)
    {
        if (item instanceof Integer)
        {
            num  =(int)item + 0.0;
        }
        else
        {
            if(item instanceof String)
            {
                // don't do anything - skip 
                continue ;
            }
            else
            {
                // is a double
                num = (double)(item) ;

            }
        }
        if(num >= max)
        {
            max = num ;
        }
    }
    System.out.println(max);

这就是我将如何使用 Java 8+ 做到这一点

Object[] array = new Object[] { 1, "2", 2.5f, 3, "test" };
double result = Stream.of(array)
                    .filter(x -> x instanceof Number)
                    .mapToDouble(x -> ((Number) x).doubleValue())
                    .max().orElse(Double.MIN_VALUE);

-> 结果=3

您可以从数组中提取floatint忽略string值,然后找到最大值和最小值。

import java.util.Arrays;
public class stackMax
{
    public static void main (String[] args)
    {
        String[] A={"1","2","3","4","4.5","4.4","NA","NA","NA"};
        System.out.println(findMax(A));
    }

public static String findMax(String[] A)
{
    int max=0,min=0; //stores minimum and maximum values
    int f=0;  //counter to store values in "float" arrays
    //store length for FloatArray so we dont get extra zereos at the end
    int floatLength =0;

    for(int i=0;i<A.length;i++){
        try{
            Float.parseFloat(A[i]);
            floatLength++;
        }
        catch(NumberFormatException e) {}
    }

    //arrays to store int and float values from main Array "A"
    float[] floatArray = new float[floatLength];
    for(int i=0;i<floatLength;i++){
        try{ //checking valid float using parseInt() method 
            floatArray[f] = Float.parseFloat(A[i]); 
            f++;
        }  
        catch (NumberFormatException e) {}      
    }
    Arrays.sort(floatArray);
    return String.format("\nMaximum value is %.1f\nMinimum value is %.1f",floatArray[floatArray.length-1],floatArray[0]);
}       
}

暂无
暂无

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

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