简体   繁体   中英

Combine two different arrays with diffrent data

I have two diffrent arrays one students name and one with there last names

String[] firstname = {"Joe", "bryan", "moe", "zoe"};
String[] Lastname = {"May", "Zoey", "Eden", "Pratt"};

I was wondering how i would go on getting an output like where it prints the students first name then right next it the students last name

eg Joe May ,Bryan Zoey

I dont want to use print function to manually print each first and last name manually. I was wondering how i could print them all at once

If you are using Java stream you can use :

String[] fullName = IntStream.range(0, firstname.length)
        .mapToObj(i -> String.format("%s %s", firstname[i], lastname[i]))
        .toArray(String[]::new);

I based in the fact the two arrays have the same size.

Outputs

[Joe May, bryan Zoey, moe Eden, zoe Pratt]

In addition to an elegant answer by @YCF_L some more ways are given below:

public class Main {
    public static void main(String[] args) {
        String[] firstNames = { "Joe", "bryan", "moe", "zoe" };
        String[] lastNames = { "May", "Zoey", "Eden", "Pratt" };

        // First method
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < firstNames.length && i < lastNames.length; i++) {
            sb.append(firstNames[i]).append(" ").append(lastNames[i]).append(", ");
        }
        sb.deleteCharAt(sb.length() - 2); // delete the last comma
        System.out.println(sb);

        // Second method
        String fullNames[] = new String[firstNames.length];
        for (int i = 0; i < firstNames.length && i < lastNames.length; i++) {
            fullNames[i] = firstNames[i] + " " + lastNames[i];
        }
        String fullNamesStr = String.join(", ", fullNames);
        System.out.println(fullNamesStr);
    }
}

Output:

Joe May, bryan Zoey, moe Eden, zoe Pratt 
Joe May, bryan Zoey, moe Eden, zoe Pratt

in java 8 ,considering the condition that arrays has same size.

ArrayList<String> al=new ArrayList<>();
  for(int i=0;i<firstname.length;i++)
   {
     al.add(fisrtname[i]+" "+lastname[i]);
   }
//now u have a complete arraylist with you with all the full names in it

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM