Sum all integers java

Java method to sum any number of ints

If your using Java8 you can use the IntStream:

int[] listOfNumbers = ; System.out.println(IntStream.of(listOfNumbers).sum()); 

Just 1 line of code which will sum the array.

public int sumAll(int. numbers) < int result = 0; for(int i = 0 ; i < numbers.length; i++) < result += numbers[i]; >return result; > 

Then call the method and give it as many int values as you need:

int result = sumAll(1,4,6,3,5,393,4,5);//. System.out.println(result); 
public int sumAll(int. nums) < //var-args to let the caller pass an arbitrary number of int int sum = 0; //start with 0 for(int n : nums) < //this won't execute if no argument is passed sum += n; // this will repeat for all the arguments >return sum; //return the sum > 
public long sum(int. numbers) < if(numbers == null)< return 0L;>long result = 0L; for(int number: numbers) < result += number; >return result; > 

Thank you. Return type had to be int. Does (int. numbers) notation work for other types such as long double and even String?

import java.util.Scanner; public class SumAll < public static void sumAll(int arr[]) System.out.println("Sum is : " + sum); > public static void main(String[] args) < int num; Scanner input = new Scanner(System.in);//create scanner object System.out.print("How many # you want to add : "); num = input.nextInt();//return num from keyboard int[] arr2 = new int[num]; for (int i = 0; i < arr2.length; i++) < System.out.print("Enter Num" + (i + 1) + ": "); arr2[i] = input.nextInt(); >sumAll(arr2); > > 
 public static void main(String args[]) < System.out.println(SumofAll(12,13,14,15));//Insert your number here. < public static int SumofAll(int. sum)//Call this method in main method. int total=0;//Declare a variable which will hold the total value. for(int x:sum) < total+=sum; >return total;//And return the total variable. > > 

You could do, assuming you have an array with value and array length: arrayVal[i] , arrayLength :

int sum = 0; for (int i = 0; i < arrayLength; i++) < sum += arrayVal[i]; >System.out.println("the sum is" + sum); 

Linked

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Читайте также:  представляет заголовок документа. Большинство элементов HTML пишутся с начальным тегом (или открывающим) и конечным тегом (или закрывающим) с содержимым между ними. Элементы могут также содержать атрибуты, которые определяют его дополнительные свойства. Например, абзац, который представлен элементом , будет…

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.7.27.43548

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

Как найти сумму чисел из массива в java?

Да, да, я знаю, что этот код — кусок бреда, который даже близко не выполняет свою функцию, но я уже голову себе сломал и далеко я не математик (и не программист). Как же мне найти сумму чисел в массиве, при условии что длина массива может быть произвольной, а числа в нем разные, не имеющие какой либо последовательности?

9 ответов 9

Честно не понял вопроса. В начале говорится — пытаюсь получить сумму некоторых чисел. а что значит некоторых?? Если всех чисел, то это очень просто сделать:

public static void testArray() < int myArray[] = ; int sum = 0; for (int i = 0; i < myArray.length; i++) < sum = sum + myArray[i]; >System.out.println(sum); > 

Ну да, наверное всех. Не так выразился. Прощу прощения, имелось ввиду, что в массиве может быть абсолютно разные числа, которые идут не по порядку и все такое.

Нажмите только это спасибо))) Если ответ вам подошел, то заодно выбор ответа, чтобы вопрос закрылся)))

В Java 8 можно в 1 строку с помощью stream

int myArray[] = ; int total = IntStream.of(myArray).sum(); 

аналогично можно использовать класс Arrays

Метод stream имеет перегрузки для примитивных типов и обобщенный вид, что подойдет для массивов других типов.

Существует несколько способов найти сумму элементов в массиве:

    Используя Java 8 Stream API (сначала с помощью метода Arrays::stream преобразовываем массив в поток целых чисел, затем получаем сумму этого потока методом Stream::sum )

int array[] = ; int sum = Arrays.stream(array).sum(); 
int array[] = ; int sum = 0; for (int element : array) sum += element; 
int array[] = ; int sum = 0; for (int i = 0; i < array.length; ++i) sum += array[i]; 
/** * Sum of all elements from 1 to 1000 */ final int sum = Stream.iterate(1, n -> n + 1).limit(1000).mapToInt(el -> el).sum(); 

Вот 3 способа, от самого примитивного, до нормального. Сильно не критикуйте, сам только учусь.

import java.util.Arrays; // сумма всех элементов массива, способ первый class BlaBlaBla1 < public static void main(String[] args) < int[] nums = ; int sum = 0; for (int i = 0; i < nums.length; i++) sum += nums[i]; System.out.println("1ый способ = " + sum); >> // сумма всех элементов массива, способ второй class BlaBlaBla2 < public static void main(String[] args) < int[] nums = ; int sum = 0; sum = Arrays.stream(nums).sum(); System.out.println("2ой способ = " + sum); > > // сумма всех элементов массива, способ третий: FOR-EACH class BlaBlaBla3 < public static void main(String[] args) < int[] nums = ; int sum = 0; for (int x : nums) sum += x; System.out.println("3ий способ = " + sum); > > 

Источник

How to sum a list of integers with java streams?

I want to sum a list of Integers. It works as follows, but the syntax does not feel right. Could the code be optimized?

Map integers; integers.values().stream().mapToInt(i -> i).sum(); 

"but the syntax does not feel right" What makes you think that? This is the usual idiom. Maybe you want to use mapToLong to avoid overflows, depending on the values your map can have.

@JBNizet I find i -> i very clear, personally. Well, yes you need to know that the value will be automatically unboxed, but it's true since Java 5.

@AlexisC. it's understandable because it's passed to mapToInt(), and because I'm an experienced developer. But i -> i, without context, looks like a noop. Integer::intValue is more verbose, but makes the unboxing operation explicit.

@JBNizet People that calls the method foo(int i) do not write foo(myInteger.intValue()); each time they call it (or at least I expect not!!). I agree with you that Integer::intValue is more explicit but I think the same applies here. People should just learn it once and then you're done :-). It's not like if it was some magic obfuscation.

@JB Nizet: well, i -> i looks like a no-op and conceptionally, it is a no-op. Sure, under the hood Integer.intValue() gets called, but even deeper under the hood, that methods gets inlined to become exactly the no-op that it looks like in the source code. Integer::intValue has the bonus point of not creating a synthetic method in the byte code but it’s not what should drive your decision of how to organize your source code.

12 Answers 12

This will work, but the i -> i is doing some automatic unboxing which is why it "feels" strange. mapToInt converts the stream to an IntStream "of primitive int-valued elements". Either of the following will work and better explain what the compiler is doing under the hood with your original syntax:

integers.values().stream().mapToInt(i -> i.intValue()).sum(); integers.values().stream().mapToInt(Integer::intValue).sum(); 

How do you sum to a particular value? for example, you have a list of integers but you want to sum till you get the value 20.

integers.values().stream().mapToInt(Integer::intValue).sum(); integers.values().stream().collect(Collectors.summingInt(Integer::intValue)); 

The second one uses Collectors.summingInt() collector, there is also a summingLong() collector which you would use with mapToLong .

And a third option: Java 8 introduces a very effective LongAdder accumulator designed to speed-up summarizing in parallel streams and multi-thread environments. Here, here's an example use:

LongAdder a = new LongAdder(); map.values().parallelStream().forEach(a::add); sum = a.intValue(); 

Reduction operations A reduction operation (also called a fold) takes a sequence of input elements and combines them into a single summary result by repeated application of a combining operation, such as finding the sum or maximum of a set of numbers, or accumulating elements into a list. The streams classes have multiple forms of general reduction operations, called reduce() and collect(), as well as multiple specialized reduction forms such as sum(), max(), or count().

Of course, such operations can be readily implemented as simple sequential loops, as in:

int sum = 0; for (int x : numbers)

However, there are good reasons to prefer a reduce operation over a mutative accumulation such as the above. Not only is a reduction "more abstract" -- it operates on the stream as a whole rather than individual elements -- but a properly constructed reduce operation is inherently parallelizable, so long as the function(s) used to process the elements are associative and stateless. For example, given a stream of numbers for which we want to find the sum, we can write:

int sum = numbers.stream().reduce(0, (x,y) -> x+y); 
int sum = numbers.stream().reduce(0, Integer::sum); 

These reduction operations can run safely in parallel with almost no modification:

int sum = numbers.parallelStream().reduce(0, Integer::sum); 

So, for a map you would use:

integers.values().stream().mapToInt(i -> i).reduce(0, (x,y) -> x+y); 
integers.values().stream().reduce(0, Integer::sum); 

What the OP has is much better, and also clearer. This code would involve a whole loat of unboxing and boxing operations.

@JBNizet Unless the escape analysis eliminates the boxing. You would have to try it to see if it can.

(x,y) -> x+y needs to unbox x and y, sum them, and then box the result. And start again to add the result with the next element of the stream, and again and again.

Integer::sum suffers from the same problem. And if you use mapToInt() to have an IntStream, calling sum() on it is more straightforward than calling reduce().

See docs.oracle.com/javase/8/docs/api/java/lang/…. The two arguments of Integer.sum() are of type int. So the two Integers from the stream must be unboxed to be passed as arguments to the method. The method returns an int, but reduce() takes a BinaryOperator as argument, which thus returns an Integer. So the result of the sum has to be boxed to Integer.

You can use reduce method:

long sum = result.stream().map(e -> e.getCreditAmount()).reduce(0L, (x, y) -> x + y); 
long sum = result.stream().map(e -> e.getCreditAmount()).reduce(0L, Integer::sum); 

You can use reduce() to sum a list of integers.

int sum = integers.values().stream().reduce(0, Integer::sum); 

You can use collect method to add list of integers.

List list = Arrays.asList(2, 4, 5, 6); int sum = list.stream().collect(Collectors.summingInt(Integer::intValue)); 

I have declared a list of Integers.

ArrayList numberList = new ArrayList(Arrays.asList(1, 2, 3, 4, 5)); 

You can try using these different ways below.

int sum = numberList.stream().mapToInt(Integer::intValue).sum(); 
int sum = numberList.stream().collect(Collectors.summarizingInt(Integer::intValue)).getSum(); 
int sum = numberList.stream().reduce(Integer::sum).get().intValue(); 

May this help those who have objects on the list.

If you have a list of objects and wanted to sum specific fields of this object use the below.

List somList = MyUtil.getResultSom(); BigDecimal result= somList.stream().map(ResultSom::getNetto).reduce( BigDecimal.ZERO, BigDecimal::add); 

This would be the shortest way to sum up int type array (for long array LongStream , for double array DoubleStream and so forth). Not all the primitive integer or floating point types have the Stream implementation though.

Unfortunately we don't have any int-array. So IntStream.of() won't work for this problem, unless we're making something spooky like this: IntStream.of( integers.values().stream().mapToInt( Integer::intValue ).toArray() ).sum();

Unfortunately looks like the Stream API only returns normal streams from, say, List#stream() . Guess they're pretty much forced to because of how generics work.

These normal Streams are of generic objects so don't have specialized methods like sum() etc. so you have to use the weird re-stream "looks like a no-op" conversion by default to get to those methods. .mapToInt(i -> i) .

Another option is using "Eclipse Collections" which are like an expanded java Stream API

There is one more option no one considered here and it reflects on usage of multi-core environment. If you want to use its advantages, then next code should be used instead of the other mentioned solutions:

int sum = integers.values().parallelStream().mapToInt(Integer::intValue) .reduce(0, Integer::sum, Integer::sum); 

This solution is similar to other ones, but please notice the third argument in reduce. It tells compiler what to do with partial summaries calculated in different chunks of the stream, by different threads. Also instead of stream() , the parallelStream() is used. In this case it would just summarize it. The other option to put as third argument is (i, j) -> i + j , which means that it would add a value of a stream chunk ( j ) to the current value ( i ) and use it as a current value for the next stream chunk until all partial results are processed.

Even when using plain stream() it is useful to tell to reduce what to do with stream chunks' summaries, just in case someone, or you, would like to parallelize it in the future. The initial development is best time for that, since later on you need to remember what this is supposed to be and need to spend some time in understanding the purpose of that code again.

And of course instead of method reference operator you can have different dialect of lambda. I prefer it this way as more compact and still easy readable.

Also remember this can be used for more complex calculations too, but always be aware there are no guarantees about sequence and deployment of stream elements to threads.

Источник

Оцените статью