How to Sum a Mixed Array in Java

1 min read 265 words

The challenge

Given an array of integers as strings and numbers, return the sum of the array values as if all were numbers.

Return your answer as a number.

The solution in Java code

Option 1 (using stream):

import java.util.List;

public class MixedSum {

  public int sum(List<?> mixed) {
    return mixed.stream().mapToInt(o -> Integer.parseInt(o.toString())).sum();
  }

}

Option 2 (the harder way):

import java.util.List;

public class MixedSum {
  public int sum(List<?> mixed) { 
      int sum = 0;
    
      for (Object element : mixed) {
        if (element instanceof Integer) {
          sum += (Integer) element;
        } else if (element instanceof String) {
          sum += Integer.parseInt( (String) element );
        }
      }
      return sum;
  }
}

Option 3 (using Objects):

import java.util.List;

public class MixedSum {

  public int sum(List<?> mixed) { 
  
    int x = 0;
    for(Object s: mixed){
            x+=Integer.parseInt(s.toString());
    }
    
    return x;  
  }
}

Test cases to validate our solution

import org.junit.Test;
import static org.junit.Assert.assertEquals;
import org.junit.runners.JUnit4;

import java.util.Arrays;

public class SolutionTest {
  
    MixedSum mixedSum = new MixedSum();

    @Test
    public void test_1() {
        assertEquals(10, mixedSum.sum(Arrays.asList(5,"5")));
    }
    
     @Test
    public void test_2() {
        assertEquals(22, mixedSum.sum(Arrays.asList(9, 3, "7", "3")));
    }
    
    @Test
    public void test_3() {
        assertEquals(42, mixedSum.sum(Arrays.asList("5", "0", 9, 3, 2, 1, "9", 6, 7)));
    }
    
    @Test
    public void test_4() {
        assertEquals(41, mixedSum.sum(Arrays.asList("3", 6, 6, 0, "5", 8, 5, "6", 2, "0")));
    }
    
    @Test
    public void test_5() {
        assertEquals(45, mixedSum.sum(Arrays.asList("1", "5", "8", 8, 9, 9, 2, "3")));
    }
    
    @Test
    public void test_6() {
        assertEquals(41, mixedSum.sum(Arrays.asList("3", 6, 6, 0, "5", 8, 5, "6", 2, "0")));
    }
    
    @Test
    public void test_7() {
        assertEquals(61, mixedSum.sum(Arrays.asList(8, 0, 0, 8, 5, 7, 2, 3, 7, 8, 6, 7)));
    }
}
Tags:
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags

Recent Posts