Using string in java array - java

I need to put several strings into a java array for example.
"Dog","Cat","Lion","Giraffe"
"Car","Truck","Boat","RV"
each of the above would be 1 key in the array
array[0] = "Dog","Cat","Lion","Giraffe"
array[1] = "Car","Truck","Boat","RV"
Not sure how to do this,or should I be using something other than an array,and how to get each individual element i.e array[0]"Lion"
Thanks

Declare the array like this:
String [][]array = {
{ "Dog","Cat","Lion","Giraffe"},
{"Car","Truck","Boat","RV"}
};
and use the items like this:
array[0][0]; // this would be "Dog"
array[1][0]; // this would be "Car"

You can use a multidimensional array:
String[][] something =
{
{ "hello", "kitties" },
{ "i", "am", "a", "pony" }
};

Well you can do it by declaring a map like so Map<String, MySweetObject> or create a List<String> and put each list into the array.

You need a jagged array, which is an array of arrays:
String [][]array = { {"Dog","Cat","Lion","Giraffe"}, {"Car","Truck","Boat","RV"}};
You can then access the content as this:
array[0] // will be the String array {"Dog","Cat","Lion","Giraffe"}
array[1] // will be the String array {"Car","Truck","Boat","RV"}
array[0][2] // Lion
array[1][0] // Car

Related

Java: Removing item from array because of character

Lets say you have an array like this: String[] theWords = {"hello", "good bye", "tomorrow"}. I want to remove/ignore all the strings in the array that have the letter 'e'. How would I go about doing that? My thinking is to go:
for (int arrPos = 0; arrPos < theWords.length; arrPos++) { //Go through the array
for (int charPos = 0; charPos < theWords[arrPos].length(); charPos++) { //Go through the strings in the array
if (!((theWords[arrPos].charAt(charPos) == 'e')) { //Finds 'e' in the strings
//Put the words that don't have any 'e' into a new array;
//This is where I'm stuck
}
}
}
I'm not sure if my logic works and if I'm even on the right track. Any responses would be helpful. Many thanks.
One easy way to filter an array is to populate an ArrayList with if in a for-each loop:
List<String> noEs = new ArrayList<>();
for (String word : theWords) {
if (!word.contains("e")) {
noEs.add(word);
}
}
Another way in Java 8 is to use Collection#removeIf:
List<String> noEs = new ArrayList<>(Arrays.asList(theWords));
noEs.removeIf(word -> word.contains("e"));
Or use Stream#filter:
String[] noEs = Arrays.stream(theWords)
.filter(word -> !word.contains("e"))
.toArray(String[]::new);
You can directly use contains() method of String class to check if "e" is present in your string. That will save your extra for loop.
It would be simple if you use ArrayList.
importing import java.util.ArrayList;
ArrayList<String> theWords = new ArrayList<String>();
ArrayList<String> yourNewArray = new ArrayList<String>;//Initializing you new array
theWords.add("hello");
theWords.add("good bye");
theWords.add("tommorow");
for (int arrPos = 0; arrPos < theWords.size(); arrPos++) { //Go through the array
if(!theWords.get(arrPos).contains("e")){
yourNewArray.add(theWords.get(arrPos));// Adding non-e containing string into your new array
}
}
The problem you have is that you need to declare and instantiate the String array before you even know how many elements are going to be in it (since you wouldn't know how many strings would not contain 'e' before going through the loop).
Instead, if you use an ArrayList you do not need to know the required size beforehand. Here is my code from start to end.
String[] theWords = { "hello", "good bye", "tomorrow" };
//creating a new ArrayList object
ArrayList<String> myList = new ArrayList<String>();
//adding the corresponding array contents to the list.
//myList and theWords point to different locations in the memory.
for(String str : theWords) {
myList.add(str);
}
//create a new list containing the items you want to remove
ArrayList<String> removeFromList = new ArrayList<>();
for(String str : myList) {
if(str.contains("e")) {
removeFromList.add(str);
}
}
//now remove those items from the list
myList.removeAll(removeFromList);
//create a new Array based on the size of the list when the strings containing e is removed
//theWords now refers to this new Array.
theWords = new String[myList.size()];
//convert the list to the array
myList.toArray(theWords);
//now theWords array contains only the string(s) not containing 'e'
System.out.println(Arrays.toString(theWords));

How can I create a new array by merging specific values

I have created two arrays with values in them.
String[] array1 = {"ab", "bc", "ca"};
String[] array2 = {"zy", "yx", "xz"};
I would like to create a third array that obtains specific values from the two arrays.
{"ab", "ca", "yx"}
Instead of simply merging two arrays, is there a way that I can pluck specific values from other arrays when creating the third array?
In Java
You would need to define an interface by which you decide which item is specific and which is not.
public interface SpecificItemDetect{
boolean isSpecific(String item);
}
Now, you can use this code to create your third array.
List<String> third = new ArrayList<String>();
for (String item : Array1){
if(detector.isSpecific(item)){
third.add(item);
}
}
for (String item : Array2){
if(detector.isSpecific(item)){
third.add(item);
}
}
// Now, you may want to convert the list to array.
String[] thirdArray = new String[third.size()];
third.toArray(thirdArray);
Note: detector in this example is an implementation of a class which implements the interface SpecificItemDetect.
In JavaScript
In JavaScript you would need a function instead of that interface. Something like this:
var filter = function(item){
if(/* item is specific */){
return true;
} else {
return false;
}
}
And create the third array like this:
var third = [];
for (var i = 0, len = Array1.length; i < len; i += 1){
if(filter(Array1[i])){
third.push(item);
}
}
for (var i = 0, len = Array2.length; i < len; i += 1){
if(filter(Array2[i])){
third.push(item);
}
}
You cannot access the memory where the array values are stored. This means, you need to go through the array name. Now, with array name you can refer to a specific value you want to 'pluck'. Do you have any rules for this??
Well, I'm not entirely sure what you mean when you say specific values, but if you mean the values that you showed only then you can do it this way
String[] array1 = {"ab", "bc", "ca"};
String[] array2 = {"zy", "yx", "xz"};
List<String> list1 = new ArrayList<String>();
String[] array3 = new String[list1.size()]; //Skip if you don't need array
list1.add(array1[0]);
list1.add(array1[2]);
list1.add(array2[1]);
list1.toArray(array3); //Skip if you don't need array
Much like what abforce said, but if you simply wanted to know how to use the .add method, that is all you need to do. But if you would like to change the values inside when the "specific values" you need change then the interface will be much better. This code is simiple but not very flexible if you need to change the values in the future.

Assignment of an array

I saw this snippet when I was preparing for one of the certification exam on java. Can anybody please explain me how does this work?
public static void main(String args[]) {
String str[] = new String[][] {
{ null },
new String[] { "a", "b", "c" },
{ new String() }
}[0];
System.out.println(str[0]);
}
The o/p is null as expected but I am confused with the assignment of String array 's'.
Is it a single dimension array or two-dimensional?
What does [0] on the righthand side of the assignment mean?
How does new String[] { "a", "b", "c" } work?
Thanks in advance
GPAR
I've split the statement into multiple lines, improving the readability
// First, the array is created, then it is stored into a variable.
// At last, store the result of code below into a String[].
String str[] =
// Create a two-dimensional array
new String[][] {
// Add the first element to the two-dimensional array,
// which is in fact a String[] with one null element in it.
/* element #0 */ new String[] { null },
// Add the second element to the two-dimensional array:
// it's a String[] containing three strings
/* element #1 */ new String[] { "a", "b", "c" },
// Then add the third element to the two-dimensional array,
// which is an empty string.
/* element #2 */ new String[] { new String() }
}
// Then get the first element of our two-dimensional array,
// which returns a String[] with one null element in it.
[0];
So in fact, variable str now contains a String[] with index 0 being null.
At last, str[0] is printed on the screen, which was null.
To answer your questions:
Variable str is a one-dimensional array. The notation String str[] is very ugly and confusing; it should be String[] str. And then you can see more easily that our variable is one-dimensional.
[0] means get the first element of the array (arrays always start with index 0). A certain element of a two-dimensional array is always a one-dimensional array; with other words, a two-dimensional array is an array containing arrays.
So that's why String[] str = new String[][] { ... }[0] is perfectly valid.
new String[] { "a", "b", "c" } creates a string array containing three strings: "a", "b" and "c".
So new String[] { "a", "b", "c" }[2] would return "c".
EDIT
Let me explain it step by step.
Step 1 — This is how we declare a String[] (a String array):
String[] myArray = new String[numberOfElements];
Step 2 — We can also immediately initialize the array with values:
String[] myArray = new String[] {
"some value",
"another value",
"et cetera"
};
Step 2b — We do not need to mention the number of elements, because the compiler already sees that we initialize the array with three elements
String[] myArray = new String[3] {
// ^
"some value", // That number
"another value", // is unnecessary.
"et cetera"
};
Step 3 — Because we declare the array and immediately initialize it, we can omit the new statement:
String[] myArray = {
"some value",
"another value",
"et cetera"
};
Step 4 — Next, we have a two-dimensional array, which is nothing more than an array of arrays.
We can first initialize the one-dimensional arrays and then dump them together in a two-dimensional array, like this:
String[] firstThree = { "a", "b", "c" };
String[] lastThree = { "x", "y", "z" };
String[][] myArray = new String[] {
firstThree,
lastThree
};
Step 5 — But we can also do that at once:
String[][] myArray = new String[] {
new String[] { "a", "b", "c" },
new String[] { "x", "y", "z" }
};
Step 6 — Now we said that we can omit the new statements (see step 3), because the array is initialized immediately after initialization:
String[][] myArray = {
{ "a", "b", "c" },
{ "x", "y", "z" }
};
Step 7 — Right?
Step 8 — Now we have your code:
String str[] = new String[][] {
{ null },
new String[] { "a", "b", "c" },
{ new String() }
}[0];
System.out.println(str[0]);
And let us rewrite your code; effectively it's the same as your piece of code.
// Let us define a new two-dimensional string array, with space for three elements:
String[][] our2dArray = new String[3][];
// Then, let us fill the array with values.
// We will add a String array with exactly one element (that element is `null` by chance)
our2dArray[0] = new String[] { null };
// We define the contents for index 1 of our2dArray
our2dArray[1] = new String[] { "a", "b", "c" };
// At last, the last element:
our2dArray[2] = new String[] { new String() };
// Which is effectively the same as
// new String[] { "" };
We have initialized the array so far.
Step 9 — But then, do you see this snippet?:
}[0];
Step 10 — That means we just grab the first element of our newly created array and store that element to our famous variable named str!
String[] str = our2dArray[0]; // Variable str now contains a
// String array (String[]) with exactly one null-element in it.
// With other words:
// str = String[] {
// 0 => null
// }
Step 11 — Then if we print index 0 of our str array, we get null.
System.out.println(str[0]); // Prints null
Step 12 — You see?
1> str is a one-dimensional array
2> the [0] returns the first element of the array (which in this case is another array)
3> new String[]{"a","b","c"} creates and initialises the string array, so that it contains the 3 specified strings - answers to this question might help you with the various syntax rules for this
This is very ugly code.
this String str[]=new String[][]{{null},new String[]{"a","b","c"},{new String()}}[0]; create and initialize a jagged 2d array of String with some initialization and [0] is there to select the 0th String[] to be assigned to the new str variable (the value will be {null}).
the second line prints some value s[0] which is declared somewhere else.

Two dimensional string array in java

I am new to java please help me with this issue.
I have a string lets say
adc|def|efg||hij|lmn|opq
now i split this string and store it in an array using
String output[] = stringname.split("||");
now i again need to split that based on '|'
and i need something like
arr[1][]=adc,arr[2][]=def and so on so that i can access each and every element.
something like a 2 dimensional string array.
I heard this could be done using Arraylist, but i am not able to figure it out.
Please help.
Here is your solution except names[0][0]="adc", names[0][1]="def" and so on:
String str = "adc|def|efg||hij|lmn|opq";
String[] obj = str.split("\\|\\|");
int i=0;
String[][] names = new String[obj.length][];
for(String temp:obj){
names[i++]=temp.split("\\|");
}
List<String[]> yourList = Arrays.asList(names);// yourList will be 2D arraylist.
System.out.println(yourList.get(0)[0]); // This will print adc.
System.out.println(yourList.get(0)[1]); // This will print def.
System.out.println(yourList.get(0)[2]); // This will print efg.
// Similarly you can fetch other elements by yourList.get(1)[index]
What you can do is:
String str[]="adc|def|efg||hij|lmn|opq".split("||");
String str2[]=str[0].split("|");
str2 will be containing abc, def , efg
// arrays have toList() method like:
Arrays.asList(any_array);
Can hardly understand your problem...
I guess you may want to use a 2-dimenison ArrayList : ArrayList<ArrayList<String>>
String input = "adc|def|efg||hij|lmn|opq";
ArrayList<ArrayList<String>> res = new ArrayList<ArrayList<String>>();
for(String strs:input.split("||")){
ArrayList<String> strList = new ArrayList<String>();
for(String str:strs.split("|"))
strList.add(str);
res.add(strList);
}

How to convert an ArrayList<T> to Object[][] in Java?

What is the easiest way to convert a Java ArrayList to Object[][]?
For example:
List<MyClass> myList = new ArrayList<MyClass>();
myList.add(myObj1);
myList.add(myObj2);
Object[][] objArray = myList.... How do I convert?
The reason I'm trying to do this is to use the QueryRunner.batch(String sql, Object[][] params) method of DBUtils.
EDIT:
See here for details:
DBUtils QueryRunner.batch()
EDIT2:
I'll try to give some more information.
public class MyObj
{
int myInt;
String myString;
}
MyObj obj1 = new MyObj(1, "test1");
MyObj obj2 = new MyObj(2, "test2");
List<MyObj> myList = new ArrayList<MyObj>();
myList.add(obj1);
myList.add(obj2);
Object[] onedArray = myList.toArray(); // Now I have a 1d array of my list of objects.
Object[] objArray = myList.get(0); // How do I convert each object instance into an array of Objects?
// Intended result would be something like this:
new Object[][] { { 1, "test1" }, { 2, "test2" } };
EDIT3:
One possible solution is this:
I could add a toObjectArray() method to MyObj class.
Surely there must be a better way?
public Object[] toObjectArray()
{
Object[] result = new Object[2];
result[0] = this.myInt;
result[1] = this.myString;
return result;
}
Thanks.
Arraylist is a single dimensional collection because it uses a single dimensional array inside. You cannot convert a single dimensional array to a two dimensional array.
You may have to add more information in case you want to do conversion of 1D to 2D array.

Categories