Merge Two String array object using java - java

public class MergeNames {
public static void main(String[] args) {
String[] names1 = new String[] { "Ava", "Emma", "Olivia" };
String[] names2 = new String[] { "Olivia", "Sophia", "Emma" };
int na1 = names1.length;
int na2 = names2.length;
String [] result = new String[na1 + na2];
System.arraycopy(names1, 0, result, 0, na1);
System.arraycopy(names2, 0, result, na1, na2);
System.out.println(Arrays.toString(result));
}
}
I created Two Array Object String and Assign Same String values. After need to merge the two String array object into another String array Object.
Note: Without no duplication
I want output like
["Ava", "Emma", "Olivia", "Sophia", "Emma"]

You can use Java Stream API the Stream.of(). See the example for better understanding.
Reference Code
public class Main {
public static <T> Object[] mergeArray(T[] arr1, T[] arr2)
{
return Stream.of(arr1, arr2).flatMap(Stream::of).distinct().toArray();
}
public static void main(String[] args) {
String[] names1 = new String[] { "Ava", "Emma", "Olivia" };
String[] names2 = new String[] { "Olivia", "Sophia", "Emma" };
Object [] result = mergeArray(names1, names2);
System.out.println(Arrays.toString(result));
}
}
Output
[Ava, Emma, Olivia, Sophia]

You have small mistake
String [] result = new String[na1 + na2];
not int

Related

How do I return string array and string to the array of multispell?

Using the main below, create the methods that will give the String[] result.
Please write the loop in the main to print the array of a multi spell.
public static void main(String[] args) {
// Create array here
// use your array to create new array here
String[] multispell = Attack(“your array”, “ball”);
Output:
Cast Fire ball!!!
Cast Ice ball!!!
Cast Earth ball!!!
Cast Lightning ball!!!
Cast Wind ball!!
my program:
public class Paper {
public static void main (String args[]) {
String[] kind = new String[5];
String [] multispell = Attack4 ( kind , "ball" );
for (int i = 0 ; i< multispell.length ; i++) {
System.out.println ("Cast " + multispell[i]+ "!!!");
}
}
public static String[] Attack4() {
String [] kind111 = {"Fire", "Ice", "Earth", "Lightning", "Wind"};
return kind111 ;
}
}
Is this what you are looking for?
public static void main(String[] args) {
String[] kind = new String[] {
"Fire", "Ice", "Earth", "Lightning", "Wind"
};
String[] multispell = Attack(kind, "ball");
for (int i = 0; i < multispell.length; i++) {
System.out.println("Cast " + multispell[i] + "!!!");
}
}
public static String[] Attack(String[] orig, String attach) {
String[] result = new String[orig.length];
for (int i = 0; i < orig.length; i++) {
result[i] = orig[i] + " " + attach;
}
return result;
}

Mysterious error that only appears when declaring the last array

When declaring an array, the IDE (Eclipse) gives me an error. However, if I declare another array immediately after, the error shifts to the next array as if by magic. I can try to add more and more arrays, but I'll only be delaying the inevitable. This leaves me with 2 questions: why does error happen and how do I fix it?
import java.util.Arrays;
public class BattleshipGrid {
private char[][] arr1 = new char[10][10];
private char[][] arr2 = new char[10][10];
private char[][] arr3 = new char[10][10];
private char[][] arr4 = new char[10][10];//"Syntax error on token ";", { expected
for (char[] i: arr2) {
for(char j: i) {
i[j]='X';
}
}
public static void main (String[] args) {
}
}
Your for loop must reside in a method of some kind.
For loop itself can't be in a class. The class is just place for declarations, not for code. Code in Java is in methods only.
So you have 2 solutions. Either put your code inside the main method:
import java.util.Arrays;
public class BattleshipGrid {
private static char[][] arr1 = new char[10][10]; // Made it static so that
// it would be bound to the class object itself, so that you can see
// it from the main method which is also static and bound to the class
// object
private static char[][] arr2 = new char[10][10];
private static char[][] arr3 = new char[10][10];
private static char[][] arr4 = new char[10][10];
public static void main (String[] args) {
for (char[] i: arr2) {
for(char j: i) {
i[j]='X';
}
}
}
}
The other (which is the better) solution is to create an instance of the class inside the main method.
import java.util.Arrays;
public class BattleshipGrid {
private char[][] arr1 = new char[10][10];
private char[][] arr2 = new char[10][10];
private char[][] arr3 = new char[10][10];
private char[][] arr4 = new char[10][10];
public void initializeTheGrid() {
for (char[] i: arr2) {
for(char j: i) {
i[j]='X';
}
}
}
public static void main (String[] args) {
BattleshipGrid grid = new BattleshipGrid();
grid.initializeTheGrid();
}
}
Try something like this:
public class BattleshipGrid
{
private char[][] arr1 = new char[10][10];
private char[][] arr2 = new char[10][10];
private char[][] arr3 = new char[10][10];
private char[][] arr4 = new char[10][10];
public static void main ( String[] args )
{
for ( char[] i: arr2)
{
for ( char j: i)
{
j = 'X';
}
}
}
}

How to sort an Array List made of String arrays?

I have a very problematic problem! I have an array list that looks like this:
ArrayList<String[]> teamsToOrder = new ArrayList<String[]>();
In each string array that is added to the ArrayList looks like this:
String[] arrayExample = {teamNumber,score};
String[] array1 = {"340","100"};
String[] array2 = {"7680","70"};
String[] array3 = {"770","110"};
...........
What I want to be able to do is organize the arrays by score (best score to worst) like so:
String[] array3 = {"770","110"};
String[] array1 = {"340","100"};
String[] array2 = {"7680","70"};
...........
How do I organize them and store them in the ArrayList? I am sorry to mention this, but my objective requires me to organize them in ArrayList form. I can't (i'm not allowed to) create a separate class for the data....
You can do it like this:
Collections.sort(teamsToOrder, new Comparator<String[]>() {
public int compare(String[] lhs, String[] rhs) {
// Parse the scores of the two items
int leftScore = Integer.parseInt(lhs[1]);
int rightScore = Integer.parseInt(rhs[1]);
// Compare the two scores, and return the result
return Integer.compare(leftScore, rightScore);
}
});
This was my original post but I edited this to make it more simple:
Here is the way to sort the ArrayList<String[]>:
Collections.sort(teamsToOrder,new Comparator<String[]>() {
public int compare(String[] s1, String[] s2) {
return Integer.parseInt(s2[1]) - Integer.parseInt(s1[1]);
}
});
That's it. So, as an example:
public static void main(String args[]) {
ArrayList<String[]> teamsToOrder = new ArrayList<String[]>();
String[] array1 = {"340","100"};
String[] array2 = {"7680","70"};
String[] array3 = {"770","110"};
teamsToOrder.add(array1);teamsToOrder.add(array2);teamsToOrder.add(array3);
Collections.sort(teamsToOrder,new Comparator<String[]>() {
public int compare(String[] s1, String[] s2) {
return Integer.parseInt(s2[1]) - Integer.parseInt(s1[1]);
}
});
// display the new sorted ArrayList of String arrays:
for (String[] s: teamsToOrder) {
System.out.println(Arrays.toString(s));
}
}
Output:
[770, 110]
[340, 100]
[7680, 70]
You should write a Comparator to compare the Strings the way you want to. Then sort your ArrayList using the implemented comparator. See: http://docs.oracle.com/javase/6/docs/api/java/util/Comparator.html
You can implement this by the following way. It is advisable to use List interface instead of ArrayList object.
public static void main(String[] args) {
// TODO Auto-generated method stub
List<String> entries = new ArrayList<String>();
entries.add("0 - name1");
entries.add("1000 - name2");
entries.add("1004 - name4");
entries.add("1002 - name3");
entries.add("10000 - name5");
entries.add("2000 - name5");
Comparator<String> comparator = new MyComparator();
Collections.sort(entries, comparator );
for (String e : entries){
System.out.println(e);
}
}

dynamically creating objects

I have a method that receives an array of strings and I need to create objects with appropriate names.
For example:
public class temp {
public static void main(String[] args){
String[] a=new String[3];
a[0]="first";
a[1]="second";
a[2]="third";
createObjects(a);
}
public static void createObjects(String[] s)
{
//I want to have integers with same names
int s[0],s[1],s[2];
}
}
If I receive ("one","two") I must create:
Object one;
Object two;
If I receive ("boy","girl") I must create:
Object boy;
Object girl;
Any help would be appreciated.
Can't do that in java. You can instead create a Map who's keys are the strings and the values are the objects.
First create Map which contains the key as String representation of Integers.
public class Temp {
static Map<String, Integer> lMap;
static {
lMap = new HashMap<String, Integer>();
lMap.put("first", 1);
lMap.put("second", 2);
lMap.put("third", 3);
}
public static void main(String[] args) {
Map<String, Integer> lMap = new HashMap<String, Integer>();
String[] a = new String[3];
a[0] = "first";
a[1] = "second";
a[2] = "third";
Integer[] iArray=createObjects(a);
for(Integer i:iArray){
System.out.println(i);
}
}
public static Integer[] createObjects(String[] s) {
// I want to have integers with same names
Integer[] number = new Integer[s.length];
for (int i = 0; i < s.length; i++) {
number[i] = lMap.get(s[i]);
}
return number;
}
}

final 2D array in Java

If I initialize an array in a Java method like:
final double[][] myArray = new double[r][c];
Will I be allowed to do this later in the method?
myArray[0] = new double[c];
Yes you can. For more on arrays http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html
I'll provide you an example of this:
public class Main {
public static void main(String[] args) {
final int[] finalArray = new int[5];
finalArray[0] = 10;
System.out.println(finalArray[0]);
finalArray[0] = 9001;
System.out.println(finalArray[0]);
finalArray = new int[5] //compile error!!!
}
}
This is because the final modifier will say that the reference to the array (the pointer) can't change, but the elements of the array (that could have another pointer) can change with no problem.
EDIT:
Another example with 2d array:
public class Main {
public static void main(String[] args) {
final int[][] array2d = new int[5][];
for(int i = 0; i < array2d.length;i++) {
array2d[i] = new int[6];
}
//the size of the rows can change with no problem.
array2d[0] = new int[8];
}
}

Categories