galo2324
galo2324

Reputation: 129

Sum of all the elements in a Vector Java

Java 11.6

I have a vector of size 8, where depending on the user input of a number between 1 to 8, my code will randomly generate values to place in a vector called vec_1.

So, for example, the output would look like

Enter the number of trials: 
>> 4 
Trials    Random Value
1           10
2           20
3            0
4           60

The values <10,20,0,60> are saved in the vector called vec_1 and then I used

Enumeration enu = vec_tor.elements();
while(enu.hasMoreElements()) {
   for (int i = 1; i<=4; i++) {
     System.out.printf("\n     " + String.valueOf(i));
     System.out.printf("      " + String.valueOf(enu.nextElement()));
   }
 }

to print out the elements from the vector side by side. I would like to add all the numbers in the vector together to get a sum so 10+20+0+60 = 90. I want to print "Sum: 90" after adding every element of the vector. I am not sure how to add element by element for a vector in java and I tried looking up other questions but they are mostly related to arrays. Any help is appreciated. Thank you!

Upvotes: 1

Views: 6381

Answers (5)

y_ug
y_ug

Reputation: 1124

Vector elements sum:

Integer sum = v.stream()    // convert to stream
  .reduce(0,Integer::sum);  // add all elements to initial zero value

Array from vector:

Integer [] a = v.toArray(new Integer[0]); // vector to array

Unit test

package example;

import org.junit.Test;

import java.util.Arrays;
import java.util.Vector;

import static org.hamcrest.MatcherAssert.*;
import static org.hamcrest.Matchers.*;

public class VectorSumTest {
    @Test
    public void sumVector() {
        Integer [] data = {10,20,0,60};
        Vector<Integer> v = new Vector<>(Arrays.asList(data));
        Integer sum = v.stream().reduce(Integer::sum).get(); // vector elements sum
        assertThat(sum, equalTo(90));
    }
}

Upvotes: 2

MC Emperor
MC Emperor

Reputation: 22977

Using the Java Streams API:

int sum = test.stream()
    .mapToInt(Integer::valueOf) // or .map(i -> i)
    .sum();

Explanation:

  • test is a Vector<Integer>.
  • Classes implementing java.util.Collection must implement the stream method. This enables the programmer to use the Stream API. Vector also implements Collection.
  • mapToInt is a method which causes all elements pulled from the stream to be mapped to the primitive int. This is represented by the IntStream class. We map Integer to just the corresponding int, either by doing i -> i (by auto-unboxing) or by Integer::valueOf.
  • IntStream implements a sum() method, which is exactly what we need.

Upvotes: 5

AbhiW
AbhiW

Reputation: 90

There are multiple ways to do it

    // using iterator
    Iterator<Integer> it = vec_tor.iterator();
    int sum = 0;
    while(it.hasNext()) {
        sum+=it.next();
    }
    System.out.println("sum:" + sum);

    // using enumeration
    sum = 0;
    Enumeration<Integer> enumeration = vec_tor.elements();
    while (enumeration.hasMoreElements()){
        sum+=enumeration.nextElement();
    }
    System.out.println("sum:" + sum);

    // using simple foreach loop
    for (int element: vec_tor) {
        sum += element; 
    }
    System.out.println("sum:" + sum);

You can use ArrayList instead of Vector here as Vector is a pretty old data structure.

Upvotes: 1

vicpermir
vicpermir

Reputation: 3702

You can add elements calling add() on the vector itself. Then you can use a stream() to add all the elements and return the total sum.

import java.util.*;

class VectorTest {
    public static void main(String[] args) {
        Vector<Integer> vec_tor = new Vector<>(); 

        vec_tor.add(10); 
        vec_tor.add(20); 
        vec_tor.add(0); 
        vec_tor.add(60); 

        System.out.println(vec_tor);

        int sum = vec_tor.stream().reduce(0, Integer::sum);
        System.out.println("Sum of vector elements: " + sum);
    }
}

The code above will output:

[10, 20, 0, 60]
Sum of vector elements: 90

Here is the documentation on Vector.add() and Stream.reduce() if you want to investigate a little bit more.

Upvotes: 1

Robert
Robert

Reputation: 42615

You can do it this way:

    Vector<Integer> vector = new Vector<>();
    // add elements

    long sum = 0;
    for (Integer x : vector) {
        sum += x; // sum = sum + x;
    }
    System.out.println("Sum: " + sum);

The for loop just iterates through every element. No need for the complicated enumeration structure. It also respects the actual element count stored in the Vector.

Note: Vector is a pretty old data structure. Nowadays usually a List like ArrayList is used.

Upvotes: 0

Related Questions