R
R
Richard Hendrix2021-05-14 21:53:03
Java
Richard Hendrix, 2021-05-14 21:53:03

What is an easy way to combine two arrays in java?

Super-simple question, but even some stupid decisions climb into my head. The bottom line is this: the function receives two arrays, you need to add each cell of one array with a cell from another array. But at the same time, I don’t know which array will be longer in order to iterate over the indices in a loop. What index to count?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
D
Dmitry Roo, 2021-05-14
@xez

I use vavr streams :

public static void main(String[] args) {
        var s1 = Stream.of(2, 1, 3); // Stream < Integer >

        var s2 = s1.zip(List.of(7, 8, 9));  // Stream <Tuple2< Integer, Integer >>

        var integers = s2.map(tuple2 -> tuple2._1 + tuple2._2).collect(Collectors.toList());

        integers.forEach(System.out::println);
    }

If the sheets are of different sizes, the remaining part is not included in the calculations.

S
Sergey_USB, 2021-05-15
@Sergey_USB

Math.max(first array, second array)

M
Madi Pagani, 2021-05-15
@prince_pagani

public static void main(String[] args) {
        var s1 = Stream.of(2, 1, 3); // Stream < Integer >

        var s2 = s1.zip(List.of(7, 8, 9));  // Stream <Tuple2< Integer, Integer >>

        var integers = s2.map(tuple2 -> tuple2._1 + tuple2._2).collect(Collectors.toList());

        integers.forEach(System.out::println);
math.max(s1,s2);
    }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question