如何在Java中的INT,Float和String阵列中找到最大和最小值



是否有一种方法可以找到由整数,浮点数和字符串或字符或字符组成的数组的最大和最小值?在Java

例如:a = {1,2,3,4,4.5,4.4,na,na,na}

因此忽略所有字符和字符串

预期结果:这里的最大元素是4.5最小值是1

这应该可以完成工作。我只考虑了int,double and strings。

    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

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

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 %.1fnMinimum value is %.1f",floatArray[floatArray.length-1],floatArray[0]);
}       
}

最新更新