T
T
ti12018-07-19 17:18:36
Java
ti1, 2018-07-19 17:18:36

How to create a method for finding the sum of array elements in Java and call it on different arrays?

In the problem of counting the queue service time from an arbitrary client at N cash desks, the queue is specified by an array of integers int[] customers, where each element customers[i] is the service time of the i-th client.
In the process of solving, it was necessary to sum the elements of the array in the case when we have N=1:

.........
        } else if (n == 1) {
            for (int i = 0; i < customers.length; i++ ) {
              sum += customers[i];
            }
        }
.........
return sum;

However, during the solution, it was necessary to find the sums of elements in two more arrays - nCustomers and restOfCustomers.
I'm creating a method that allows you to sum the elements of an arbitrary array:
public int sumOfArray(int ary[]) {
    int s = 0;
      for (int i = 0; i < ary.length; i++) {
        s += ary[i];
      }
      return s;
  }

How can I now syntactically correctly call it on all three arrays in the code - customers, nCustomers and restOfCustomers?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
illuzor, 2018-07-19
@iLLuzor

If I understand correctly and you need the sum of the elements of three arrays, then:
Or you can create a method with varargs that will calculate the sum of an arbitrary number of arrays:

public int sumOfArray(int[]... ary) {
        /// your code
    }

Or count through streams:
int sumOfAll = IntStream.of(arr1).sum() + IntStream.of(arr2).sum() + IntStream.of(arr3).sum();

A
Alexey Cheremisin, 2018-07-19
@leahch

I do this now

List<String> list  = new ArrayList<>();
    list.add("1");
    list.add("2");
    list.add("4");
    list.add("1");
    
    int summ = list.stream()
        .map(s -> Integer.parseInt(s)) // перевод из String в int
        .reduce( (s1,s2) ->  s1 + s2 ) // сумма
        .orElse(0); // значение по умолчанию
    System.out.println(summ);

Instead of list - use your collection of objects.
And inside map(....) take the desired field value.
ZYYU If with objects, then this is how you can
public class Reduce {
  public static class Offer {
    int price;
    public Offer (int price) {
      this.price = price;
    }
    
    public int getPrice() {
      return price;
    }
  }
  public static void main(String args[]) {
    List< Offer > list  = new ArrayList<>();
    list.add(new Offer(1));
    list.add(new Offer(2));
    list.add(new Offer(4));
    list.add(new Offer(1));
    
    int summ = list.stream()
        .map(Offer::getPrice) // взять прайс
        .reduce( (s1,s2) ->  s1 + s2 ) // сумма
        .orElse(0); // значение по умолчанию
    
    System.out.println(summ);
  }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question