How to send muliples values to a method and recived multiple values in different vars in Java

60 views Asked by At

Hello there I am new in Java and I am locking a way to send multiples parameters to a method but this method need to return some values too , example:

var1,var2,var3 = convertTonegative(varx,vary,varz);

So in this case after some check into the method this method need to return 3 values to each var, means:

varx after checked assign the value to var1

vary after checked assign the value to var2

varz after checked assign the value to var3

I just create a class that can received any values, but I do not how to return those values.

public class converToNegative{
    
    public converToNegative(String... args) {  // Constructor
        convertAll(args);
    }
    
    private String[] convertAll(String[] args) {
        for (int i = 0; i < args.length; i++){
            if (args[i].equals("") || args[i] == null) {
                args[i] = "-1";
            }
        }
        return args;
    }

}
1

There are 1 answers

0
Guru Rai On

I get what you're looking to do. In my early days with learning Java, I also wanted to do the same, but always felt that this is a missing feature in the language. But later I realized that while this adds complexity to the syntax of the language, the task can still be achieved without returning multiple values from the method.

Personally, I feel the best way to do this would be using Streams. You could just stream a list, use a mapping function to modify the values if conditions are met, and return back the list.

public static void main(String[] args) {
        String[] list = new String[]{"1", "2", "3", "-5", "", null};
        List<String> processedList = Arrays.asList(list).stream().map(num -> (num!=null && num!="") ? num : "-1").collect(Collectors.toList());
        System.out.println("processedList: " + processedList);
    }

But if you're just learning Java, or want to do it using the same approach, I guess there's no other way but to refactor the code to call the method one by one for all the arguments. Something like this:

public class converToNegative{
    
    public converToNegative(String... args) {  // Constructor
        convertAll(args);
    }
    
    private String[] convertAll(String[] args) {
        for (int i = 0; i < args.length; i++){
            args[i] = convert(args[i]);
        }
        return args;
    }
    
    private String convert(String num) {
        if (args[i].equals("") || args[i] == null)
            return "-1";
        else
            return num;
    }

}