AeNet Phornphithak
AeNet Phornphithak

Reputation: 27

Sum each element of two List<Integer>s into a new list

How to merge two lists to one list by included value of same index.
I have 2 lists and I want to merge two lists by included value of same index.
(If possible, please suggest me on way of java 8: Streams.)

List<String> a = Arrays.asList("1", "2", "3");
List<String> b = Arrays.asList("10", "20", "30");

Output :

{"11", "22", "33"}

Upvotes: 0

Views: 2571

Answers (3)

Donald Raab
Donald Raab

Reputation: 6686

If you use Eclipse Collections you can use zip:

List<String> a = Arrays.asList("1", "2", "3");
List<String> b = Arrays.asList("10", "20", "30");
List<String> c = Lists.adapt(a).zip(b)
        .collectInt(p -> Integer.parseInt(p.getOne()) +Integer.parseInt(p.getTwo()))
        .collect(Integer::toString);

System.out.println(c);

Output: [11, 22, 33]

You can also use Collectors2 from Eclipse Collections with a Stream.

List<String> a = Arrays.asList("1", "2", "3");
List<String> b = Arrays.asList("10", "20", "30");
List<String> c = a.stream().collect(Collectors2.zip(b))
        .collectInt(p -> Integer.parseInt(p.getOne()) + Integer.parseInt(p.getTwo()))
        .collect(Integer::toString);

System.out.println(c);

Output: [11, 22, 33]

Note: I am a committer for Eclipse Collections.

Upvotes: 1

syntagma
syntagma

Reputation: 24324

A solution that uses only standard library:

List<String> a = Arrays.asList("1", "2", "3");
List<String> b = Arrays.asList("10", "20", "30");

List<String> c = IntStream.range(0, a.size())
                          .map(i -> Integer.parseInt(a.get(i)) + Integer.parseInt(b.get(i)))
                          .mapToObj(Integer::toString)
                          .collect(Collectors.toList());

Note that input lists store numbers as String, as specified in your example. Also, you could merge map() and mapToObj() calls into a single mapToObj() call but I wanted to leave it split for clarity.

It also assumes that both lists are of the same size, if they weren't, ArrayIndexOutOfBoundsException will be thrown.

Upvotes: 3

developer_hatch
developer_hatch

Reputation: 16224

Did you try to use zip? https://github.com/poetix/protonpack has a nice library

StreamUtils.zip(a.stream(), b.stream(), (e1,e2) -> (Integer.parseInt(e1) + Integer.parseInt(e2)).toString())

Upvotes: 2

Related Questions