Сумма элементов числа java

Как сложить числа из массива java

В Java есть несколько способов найти сумму элементов массива. Например, можно использовать Stream API:

class Calculator  public static int sum(int[] numbers)  // Преобразуем массив в стрим целых чисел, а затем получаем сумму этого потока return Arrays.stream(numbers).sum(); > > int[] numbers = 1, 2, 3>; Calculator.sum(numbers); // 6 

Также можно использовать цикл, чтобы пройтись по всем элементам массива:

class Calculator  public static int sum(int[] numbers)  // Объявляем переменную для хранения суммы элементов int sum = 0; // Проходим по элементам массива и каждый к сумме for (int number: numbers)  sum += number; > return sum; > > int[] numbers = 1, 2, 3>; Calculator.sum(numbers); // 6 

Источник

Суммирование чисел с помощью стримов Java

Суммирование чисел с Stream в Java

В этом коротком руководстве мы рассмотрим различные способы вычисления суммы целых чисел с помощью Stream API.

Для простоты в наших примерах мы будем использовать Integer числа, однако можно применить те же методы и к типам Long и Double.

Использование Stream.reduce()

Stream.reduce() – это терминальная операция, которая выполняет сокращение элементов в стриме.

Операция применяет бинарный оператор (аккумулятор) к каждому элементу в стриме, где первый операнд является возвращаемым значением предыдущего элемента, а второй – текущим элементом стрима.

В первом примере функция-аккумулятор представляет собой лямбда-выражение, которое складывает два целых значения и возвращает также целое значение:

List ints = Arrays.asList(1, 2, 3, 4); Integer sum = ints.stream() .reduce(0, (a, b) -> a + b);

Таким же образом мы можем использовать статический Java-метод Integer::sum:

List ints = Arrays.asList(1, 2, 3, 4); Integer sum = ints.stream() .reduce(0, Integer::sum);

Или мы можем определить и использовать наш пользовательский метод:

public class MathUtils < public static int add(int a, int b) < return a + b; >> //. List ints = Arrays.asList(1, 2, 3, 4); Integer sum = ints.stream() .reduce(0, MathUtils::add);

Использование Stream.collect()

Второй способ вычисления суммы списка целых чисел заключается в использовании терминальной операции collect():

List ints = Arrays.asList(1, 2, 3, 4); Integer sum = ints.stream() .collect(Collectors.summingInt(Integer::intValue));

Аналогично, класс Collectors предоставляет методы summingLong() и summingDouble() для вычисления сумм коллекций типов Long и Double соответственно.

Использование IntStream.sum()

Stream API предоставляет нам промежуточную операцию mapToInt(), которая преобразует наш стрим в объект IntStream.

Этот метод принимает mapper в качестве параметра, который он использует для выполнения преобразования, затем мы можем вызвать метод sum() для вычисления суммы элементов стрима.

Давайте посмотрим на короткий пример того, как мы можем его использовать:

List ints = Arrays.asList(1, 2, 3, 4); Integer sum = ints.stream() .mapToInt(Integer::intValue) .sum();

Таким же образом мы можем использовать методы mapToLong() и mapToDouble() для вычисления сумм коллекций типов Long и Double соответственно.

Использование Stream#sum с map

Чтобы вычислить сумму значений структуры данных Map , сначала мы создадим стрим из значений этого map. Далее применим один из методов, которые мы использовали ранее. Например, IntStream.sum():

Integer sum = map.values() .stream() .mapToInt(Integer::valueOf) .sum();

Использование Stream#sum с объектами

Давайте представим, что у нас есть список объектов и мы хотим вычислить сумму всех значений выбранного поля этих объектов.

public class Item < private int id; private Integer price; public Item(int id, Integer price) < this.id = id; this.price = price; >// стандартные геттеры и сеттеры >

Далее давайте представим, что мы хотим рассчитать итоговую цену всех товаров из следующего списка:

Item item1 = new Item(1, 5); Item item2 = new Item(2, 10); Item item3 = new Item(3, 15); Item item4 = new Item(4, 20); List items = Arrays.asList(item1, item2, item3, item4);

Чтобы вычислить сумму, используя методы, показанные в предыдущих примерах, нам нужно вызвать метод map() для преобразования нашего стрима в стрим целых чисел.

Можно использовать Stream.reduce(), Stream.collect() и IntStream.sum() для вычисления суммы:

Integer sum = items.stream() .map(x -> x.getPrice()) .reduce(0, ArithmeticUtils::add); sum = items.stream() .map(x -> x.getPrice()) .reduce(0, Integer::sum); sum = items.stream() .map(item -> item.getPrice()) .reduce(0, (a, b) -> a + b); sum = items.stream() .map(x -> x.getPrice()) .collect(Collectors.summingInt(Integer::intValue)); sum = items.stream() .mapToInt(x -> x.getPrice()) .sum();

Заключение

В этой статье мы рассмотрели несколько методов вычисления суммы списка целых чисел с помощью Stream API. Мы также использовали эти методы для вычисления суммы значений выбранного поля списка объектов и суммы значений map.

Источник

Сумма элементов числа java

Learn Latest Tutorials

Splunk tutorial

SPSS tutorial

Swagger tutorial

T-SQL tutorial

Tumblr tutorial

React tutorial

Regex tutorial

Reinforcement learning tutorial

R Programming tutorial

RxJS tutorial

React Native tutorial

Python Design Patterns

Python Pillow tutorial

Python Turtle tutorial

Keras tutorial

Preparation

Aptitude

Logical Reasoning

Verbal Ability

Company Interview Questions

Artificial Intelligence

AWS Tutorial

Selenium tutorial

Cloud Computing

Hadoop tutorial

ReactJS Tutorial

Data Science Tutorial

Angular 7 Tutorial

Blockchain Tutorial

Git Tutorial

Machine Learning Tutorial

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures tutorial

DAA tutorial

Operating System

Computer Network tutorial

Compiler Design tutorial

Computer Organization and Architecture

Discrete Mathematics Tutorial

Ethical Hacking

Computer Graphics Tutorial

Software Engineering

html tutorial

Cyber Security tutorial

Automata Tutorial

C Language tutorial

C++ tutorial

Java tutorial

.Net Framework tutorial

Python tutorial

List of Programs

Control Systems tutorial

Data Mining Tutorial

Data Warehouse Tutorial

Javatpoint Services

JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.

  • Website Designing
  • Website Development
  • Java Development
  • PHP Development
  • WordPress
  • Graphic Designing
  • Logo
  • Digital Marketing
  • On Page and Off Page SEO
  • PPC
  • Content Development
  • Corporate Training
  • Classroom and Online Training
  • Data Entry

Training For College Campus

JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week

Like/Subscribe us for latest updates or newsletter RSS Feed Subscribe to Get Email Alerts Facebook Page Twitter Page YouTube Blog Page

Источник

Как найти сумму цифр числа java

Сумму цифр числа можно найти, суммируя остаток от деления на 10 :

public class App  public static void main(String[] args)  System.out.println(sumOfDigits(123)); // => 6 > public static int sumOfDigits(int number)  number = Math.abs(number); int sum = 0; while (number > 0)  sum += number % 10; number /= 10; > return sum; > > 

Источник

Sum a List of numbers in Java

wordpress-sync/Java-engineering-feature

Every now and then, I need to do some basic stuff in Java and I wonder what is the best way to this. This happened to me a few days ago! I needed to simply get the sum of a List of numbers and I found out there are a number of ways — pun intended — to do this.

The old-fashioned approach

We can create a simple loop to do this. I am using Java 11 so, forgive me if you are using, for example, Java 8, and the List.of and var does not work in your case. Nonetheless, I believe you’ll still get the point.

var listOfNumbers = List.of(1,2,3,4,5,6,7,8,9,10); var sum = 0; for (int i = 0; i < listOfNumbers.size() ; i++)  sum += listOfNumbers.get(i); >

Obviously, since Java 5, we have enhancements for loops so, I can rewrite the same code like this.

var listOfNumbers = List.of(1,2,3,4,5,6,7,8,9,10); var sum = 0; for (int number : listOfNumbers)  sum += number; >

The difference is subtle. However, it is already more expressive as it says something like «of each number coming from listOfNumbers I want to do the following . «.

The Java Stream approach

People who know me, know that I was brainwashed, during my university days, with programming in Haskell. This means I have a lot of love for pure functional programming. Not that Java can handle that ?, but the expressiveness of functional programming is somewhat available using the stream API.

With the stream API in Java, we can execute the MapReduce programming model. For the issue I am trying to solve here, I do not need to map as the numbers will stay as they are. I do, however, have to reduce the List into a single number, the sum.

Collect

In probably 99% of the cases, we use the collect function with the standard toList() collector to reduce our stream back into a List.Similar to this:

 var time2ToList = listOfNumbers.stream() .map(i -> i * 2) .collect(Collectors.toList());

However, there is more to life than collecting a stream back into a List. Browsing the Collectors library you can find functions like summingInt() , summingDouble() and summingLong() .You can use these functions to collect (or reduce) the List into the sum.

The summmingInt function does require a function that turns the input you have into an int . In this case, I can simply use «identity function». The function i -> i will be sufficient.

 var listOfNumbers = List.of(1,2,3,4,5,6,7,8,9,10); var sum = listOfNumbers.stream() .collect(Collectors.summingInt(i -> i));

This identity function might look silly so, you can use Integer.intValue() instead.

 var listOfNumbers = List.of(1,2,3,4,5,6,7,8,9,10); var sum = listOfNumbers.stream() .collect(Collectors.summingInt(Integer::intValue));

When I do this, my IDE—IntelliJ IDEA in my case—advises me to refactor this and use the mapToInt() function like seen below:

 var listOfNumbers = List.of(1,2,3,4,5,6,7,8,9,10); var sum = listOfNumbers.stream() .mapToInt(Integer::intValue).sum();

Technically what we do here is mapping every item to an int, what it already is ¯\(ツ)/¯ right, and reduce it with the sum() function.

It gets more clear if you look at the inferred types. You simply cannot have a List of primitives. So, the List is a list of Integer (the Object). This means that every item in the list needs to get back to the primitive int to make the sum() possible. The previous example with the identity function in the collector works because of Java unboxing.

If you prefer using primitive Lists in Java, I suggest taking a look at the Eclipse Collections library.

Reduce

Reduction in Java is achieved by a couple of function in the stream API.In addition to collect() , there is also the obviously-named function reduce() .

 var listOfNumbers = List.of(1,2,3,4,5,6,7,8,9,10); var sum = listOfNumbers.stream() .reduce(0 , (num1, num2) -> num1 + num2);

The reduce function in this case takes a starting point and BiFunction lambda expression. The BiFunction is applied to the starting point and the first number,he result of the function is applied to the second number, and so on.

The code above does something like this:0 + 11 + 23 + 36 + 4etc …

Now, you can omit the starting point 0 . However, the reduce function will return an Optional in this case as the List it tries to reduce might be empty.

Conclusion

As you can see, there are multiple ways to solve this problem. Without any doubt, people will come up with even more exotic ways to solve this. My personal favorite is the reduce() option. For me, this is the most expressive and pure solution in Java. I simply want to reduce a list to a single number and don’t need to care of the transformations from boxed types to primitives. Furthermore, I can reuse this approach when I need to reduce a List of other types by writing a reduction lambda function that fits my needs.

Источник

Читайте также:  Input type submit css оформление
Оцените статью