IT박스

반복하지 않고 ArrayList의 합계 가능성이 있습니까?

itboxs 2020. 10. 26. 07:47
반응형

반복하지 않고 ArrayList의 합계 가능성이 있습니까?


의 합이 ArrayList반복되지 않을 가능성이 있습니까?

PHP는 sum(array)배열의 합계를 제공합니다.

PHP 코드는 다음과 같습니다.

$a = array(2, 4, 6, 8);
echo "sum(a) = " . array_sum($a) . "\n";

Java에서도 똑같이하고 싶었습니다.

List tt = new ArrayList();
tt.add(1);
tt.add(2);
tt.add(3);

이 출시 되면 (2014 년 3 월) 스트림사용할 수 있습니다 .

당신이 List<Integer>

int sum = list.stream().mapToInt(Integer::intValue).sum();

그것이 int[]

int sum = IntStream.of(a).sum();

그런 다음 직접 작성하십시오.

public int sum(List<Integer> list) {
     int sum = 0; 

     for (int i : list)
         sum = sum + i;

     return sum;
}

다음과 같은 유틸리티 함수를 작성하십시오.

public class ListUtil{

    public static int sum(List<Integer> list){
      if(list==null || list.size()<1)
        return 0;

      int sum = 0;
      for(Integer i: list)
        sum = sum+i;

      return sum;
    }
}

그런 다음

int sum = ListUtil.sum(yourArrayList)

루프를 사용하는 유일한 대안은 재귀를 사용하는 것입니다.

다음과 같은 방법을 정의 할 수 있습니다.

public static int sum(List<Integer> ints) {
   return ints.isEmpty() ? 0 : ints.get(0) + ints.subList(1, ints.length());
}

이것은 일반 루프를 사용하는 것에 비해 매우 비효율적이며 목록에 많은 요소가 있으면 폭발 할 수 있습니다.

스택 오버플로를 피하는 대안은 사용하는 것입니다.

public static int sum(List<Integer> ints) {
    int len = ints.size();
    if (len == 0) return 0;
    if (len == 1) return ints.get(0);
    return sum(ints.subList(0, len/2)) + sum(ints.subList(len/2, len));
}

이것은 비효율적이지만 스택 오버플로를 방지합니다.


같은 것을 쓰는 가장 짧은 방법은

int sum = 0, a[] = {2, 4, 6, 8};

for(int i: a) {
    sum += i;
}

System.out.println("sum(a) = " + sum);

인쇄물

sum(a) = 20

나에게 가장 명확한 방법은 다음과 같습니다.

doubleList.stream().reduce((a,b)->a+b).get();

또는

doubleList.parallelStream().reduce((a,b)->a+b).get();

It also use internal loops, but it is not possible without loops.


You can use apache commons-collections API.

class AggregateClosure implements org.apache.commons.collections.Closure {
        int total = 0;

        @Override
        public void execute(Object input) {
            if (input != null) {
                total += (Integer) input;
            }
        }

        public int getTotal() {
            return total;
        }
    }

Then use this closure as shown below:

public int aggregate(List<Integer> aList) {
        AggregateClosure closure = new AggregateClosure();
        org.apache.commons.collections.CollectionUtils.forAllDo(aList, closure);
        return closure.getTotal();
}

If you know about the map function, then you know that a map is also can be recursive loop or recursive loop. But obviously you have to reach each element for that. so, I could not work out the Java 8, because some syntax mismatch but wanted a very short so this is what I got.

int sum = 0
for (Integer e : myList) sum += e;

Given that a list can hold any type of object, there is no built in method which allows you to sum all the elements. You could do something like this:

int sum = 0;

for( Integer i : ( ArrayList<Integer> )tt ) {
  sum += i;
}

Alternatively you could create your own container type which inherits from ArrayList but also implements a method called sum() which implements the code above.


ArrayList is a Collection of elements (in the form of list), primitive are stored as wrapper class object but at the same time i can store objects of String class as well. SUM will not make sense in that. BTW why are so afraid to use for loop (enhanced or through iterator) anyways?


This link shows three different ways how to sum in java, there is one option that is not in previous answers using Apache Commons Math..

Example:

public static void main(String args []){
    List<Double> NUMBERS_FOR_SUM = new ArrayList<Double>(){
         {
            add(5D);
            add(3.2D);
            add(7D);
         }
    };
    double[] arrayToSume = ArrayUtils.toPrimitive(NUMBERS_FOR_SUM
            .toArray(new Double[NUMBERS_FOR_SUM.size()]));    
    System.out.println(StatUtils.sum(arrayToSume));

}

See StatUtils api


You can use GNU Trove library:

TIntList tt = new TIntArrayList();
tt.add(1);
tt.add(2);
tt.add(3);
int sum = tt.sum();

Or switch to Groovy, it has a sum() function on a collection. [1,2,3,4,5,6].sum()

http://groovy.codehaus.org/JN1015-Collections

Runs on the same JVM as your java classes.

참고 URL : https://stackoverflow.com/questions/5963847/is-there-possibility-of-sum-of-arraylist-without-looping

반응형