0

I want to combine elements of two arrays "turn by turn".

result must be: [a,1,b,2,c,3,d,4,e,5]

    int[] mas1 = {1,2,3,4,5};
    String[] mas2 ={"a","b","c","d","e"};

    System.out.print("[");
    for (int i = 0; i <mas1.length ; i++) {
        System.out.print(mas2[i]+","+mas1[i]+",");

    }
    System.out.println("]");

It`s working. But is there another smart way to realize it ?

Oleg Khegay
  • 119
  • 4
  • Possible duplicate of [Interleave two arrays](https://stackoverflow.com/questions/25733806/interleave-two-arrays) – Adi219 Aug 04 '18 at 10:39
  • @Adi219 i dont need to shuffle them. Just place in series, one after another. – Oleg Khegay Aug 04 '18 at 10:44
  • The dupe isn't about shuffling, it's about interleaving the two arrays (which is what you're trying to do here). – Adi219 Aug 04 '18 at 10:46
  • @Adi219 the end result here is to print the content of the arrays (or perhaps to generate a string of them) and not to combine them into a new array as I understand it. – Joakim Danielson Aug 04 '18 at 11:06
  • @JoakimDanielson I'm not an expert in Java, but I'm fairly certain that OP could just print the new array and get the desired result (as would happen in python) – Adi219 Aug 04 '18 at 11:10
  • @Adi219 True but creating a new array just to print it doesn’t seem like an improvement to the original code. – Joakim Danielson Aug 04 '18 at 11:12
  • @JoakimDanielson You're right, but tbh the question doesn't seem appropriate for this site (I'd have thought codereview would suit it better) – Adi219 Aug 04 '18 at 11:14
  • Not sure what you consider "smarter" but one simple change is to loop to `length - 1` instead and print the last pair of items after the for loop so you can avoid that trailing `, ` – Joakim Danielson Aug 04 '18 at 11:34
  • Do you want a new array of Strings with the interchanged elements, or to just print the elements of 2 lists interchangeably? – Soutzikevich Aug 04 '18 at 13:38

3 Answers3

0

if you want to create a new combined array of String type then you can check below, please note array stores elements of the same type (for Arrays class use: import java.util.Arrays;)

    int[] mas1 = { 1, 2, 3, 4, 5 };
    String[] mas2 = { "a", "b", "c", "d", "e" };

    String[] combinedArray = new String[mas1.length + mas2.length];

    int mas1_index = 0;
    int mas2_index = 0;

    for (int i = 0; i < combinedArray.length; i++) {

        if (i % 2 == 0&&mas2_index<mas2.length) {
                combinedArray[i] = mas2[mas2_index++];
        } else if(mas1_index <mas1.length ) {
                combinedArray[i] = Integer.toString(mas1[mas1_index++]);
        }
    }
    System.out.println(Arrays.toString(combinedArray)); // output -> [a, 1, b, 2, c, 3, d, 4, e, 5]
irfan
  • 878
  • 9
  • 10
0

Using the stream api, you could flatMap the both into one by index. Below solution depends on both arrays having the same size

int[] mas1 = {1,2,3,4,5};
String[] mas2 ={"a","b","c","d","e"};
String[] combined = IntStream.range(0, mas1.length)
        .boxed()
        .flatMap(i -> Stream.of(mas2[i], String.valueOf(mas1[i])))
        .toArray(String[]::new);

If you want to keep types, you can stream to an object array too

Object[] combined = IntStream.range(0, mas1.length)
        .boxed()
        .flatMap(i -> Stream.of(mas2[i], mas1[i]))
        .toArray();
baao
  • 71,625
  • 17
  • 143
  • 203
0

@Bambam has proposed some really good solutions and I would definitely apply one of them, if what you want always has to do with 2 same-sized arrays.

However, in case you want two have to different-sized arrays and independent of their type, you could use a solution similar to this:

public List<String> addRecursively(int index, Object[] array1, Object[] array2, List<String> list){
    if(index < array1.length)
        list.add(String.valueOf(array1[index]));
    if(index < array2.length)
        list.add(String.valueOf(array2[index]));
    if(index >= array1.length && index >= array2.length)
        return list;

    return addRecursively(index+1, array1, array2, list);
}

Here is an example of how to use this method:

Integer[] arrayOfIntegers = new Integer[]{1,2,3,4,5};
String[] arrayOfStrings = new String[]{"a","b","c","d","e","f","g","h"};
List<String> unified = addRecursively(0,arrayOfStrings,arrayOfIntegers,new ArrayList<String>);

//output = a1b2c3d4e5f6g
for(String str:unified) System.out.print(str)
//output = [a, 1, b, 2, c, 3, d, 4, e, 5, f, 6, g]
System.out.println(Arrays.toString(list.toArray())); 

PLEASE NOTE: You cannot use primitive types with this method. You arrays need to have wrapped primitive data types, something achieved with boxing. If your arrays are already instantiated as primitive types, you could convert them in Java 8 like this:

int [] primitive = //some value here;
Integer[] wrapped = IntStream.of(primitive).boxed().toArray(Integer[]::new);

And you could definitely use a HashMap like the one from this answer and implement it in the aforementioned method.

I hope everyone finds this answer simple and comprehensible.

Soutzikevich
  • 991
  • 3
  • 13
  • 29