0

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

e.g 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

3 Answers 3

3

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] 
Sign up to request clarification or add additional context in comments.

Comments

1

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 

Comments

0

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 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.