Is it possible to have an array containing names or reference to other arrays?
e.g.
String[] fruits={"orange","apple"};
String[] colors={"red","blue","green"};
And the 3rd array String[] array1={"fruits","colors"};
I actually have many arrays and based on the array passed I need to compare it with the array already present.
Like if I pass a fruit array then compare array1[0]th array i.e fruits array to the passed array?
I can compare the passed array to individual arrays and perform comparison for each but is there a shorter way?
Like suggested in my comment below the question, you can use a map:
String[] fruits = {"orange", "apple"};
String[] colors = {"red", "blue", "green"};
Map<String, String[]> map = new HashMap<>();
map.put("fruits", fruits);
map.put("colors", colors);
String[] toCompare = map.get("fruits"); // will return the fruits array
You can have an array of arrays:
String[][] myArr = {fruits, colors};
But as #jlordo suggested, it's a better approach to have a Map that contains a String key which will represent the array's name, and the actual array as the value.
Since double array has already been presented as well as a map example lets see an example with arraylist.
String[] fruits = {"orange", "apple"};
String[] colors = {"red", "blue", "green"};
ArrayList<String[]> fruitsAndColors = new ArrayList<String[]>();
fruitsAndColors.add(fruits);
fruitsAndColors.add(colors);
You can read the java API for other insertion methods: http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html
You can have an array with references to almost anything using Object class (you are not limited to arrays of String):
Object [] myArr = {fruits, colors};
Related
I'm trying to convert a nested list into a 2d array.
List<List<String>> list = new ArrayList<>();
list.add(Arrays.asList("a", "b", "c"));
list.add(Arrays.asList("dd"));
list.add(Arrays.asList("eee", "fff"));
I want to make this a String[][]. I've tried the following:
String[][] array = (String[][]) list.toArray(); // ClassCastException
String[][] array = list.toArray(new String[3][3]); // ArrayStoreException
String[][] array = (String[][]) list.stream() // ClassCastException
.map(sublist -> (String[]) sublist.toArray()).toArray();
Is there a way that works? Note that I won't know the size of the list until runtime, and it may be jagged.
You could do this:
String[][] array = list.stream()
.map(l -> l.stream().toArray(String[]::new))
.toArray(String[][]::new);
It creates a Stream<List<String>> from your list of lists, then from that uses map to replace each of the lists with an array of strings which results in a Stream<String[]>, then finally calls toArray(with a generator function, instead of the no-parameter version) on that to produce the String[][].
There is no simple builtin way to do what you want because your list.toArray() can return only array of elements stored in list which in your case would also be lists.
Simplest solution would be creating two dimensional array and filling it with results of toArray from each of nested lists.
String[][] array = new String[list.size()][];
int i = 0;
for (List<String> nestedList : list) {
array[i++] = nestedList.toArray(new String[0]);
}
(you can shorten this code if you are using Java 8 with streams just like Alex did)
This is the best and most efficient way to convert 2d list to 2d array;
List<List<Integer>> list2d = new ArrayList<>();
Integer[][] array2d;
array2d = list2d.stream().map(x->x.toArray(new Integer[x.size()])).toArray(Integer[][]::new);
I know there is a String split method that returns an array but I need an ArrayList.
I am getting input from a textfield (a list of numbers; e.g. 2,6,9,5) and then splitting it at each comma:
String str = numbersTextField.getText();
String[] strParts = str.split(",");
Is there a way to do this with an ArrayList instead of an array?
You can create an ArrayList from the array via Arrays.asList:
ArrayList<String> parts = new ArrayList<>(
Arrays.asList(textField.getText().split(",")));
If you don't need it to specifically be an ArrayList, and can use any type of List, you can use the result of Arrays.asList directly (which will be a fixed-size list):
List<String> parts = Arrays.asList(textField.getText().split(","));
There is no such thing as a Split functionfor list, but you can do the split and then convert to a List
List myList = Arrays.asList(myString.split(","));
I dont know how to do this. But what i want is to create a two array.. one for the array class then the other is for the information that i will use for the selected class using for loop. I prefer for loop that for each loop.. ^_^.. My question is. Is it posible to create an array in which it will store an array too? for example:
private final Class<?>[] cls = {class1,class2,class3};
private final String[] myFirstArray = {array1[],array2[],array[]3};
private final String selectedarray[];
for(int i=0;i<cls.lenght();i++){
if(myArrayClassParameter == cls[i]){
selectedArray[] = myFirstArray[i];
}
}
Like that?
Well If it is posible my work will be less time consuming.. thanks.
Absolutely - you can create arrays of arrays, or even arrays of arrays of arrays, and so on. All you need is to add more pairs of square brackets [].
private final String[][] firstArray = new String[][] {
new String[] {"quick", "brown", "fox"}
, new String[] {"jumps", "over", "the"}
, new String[] {"lazy", "dog", "!"}
};
String[] selectedArray = firstArray[1];
Yes. These are called multidimensional arrays. Try them out and mess around with them. You'll learn better that way.
You must declare them like this:
Type[] smallerArray1;
Type[] smallerArray2;
Type[] smallerArray3;
Type[][] biggerArray = new Type[][]{smallerArray1, smallerArray2, smallerArray3};
Then you can use them like regular arrays.
In Java, what's the qucikest way to convert an array to a List or a set?
String[] a = {"Test1", "test2"};
List<String> l = new ArrayList<String>();
Use the java.util.Arrays class.
List<String> list = Arrays.asList(new String[] {"a", "b"});
Note that the implementation of List you get by the above method isn't the same as java.util.ArrayList. If you want ArrayList implementation, use
List<String> list = new ArrayList<String>(Arrays.asList(new String[] {"a", "b"}));
To convert an array to a list use Arrays.asList:
String[] a = {"Test1", "test2"};
List<String> list = Arrays.asList(a);
To convert an array to a set:
Set<String> set = new HashSet<String>(Arrays.asList(a));
From the Arrays class (doc):
List<String> l = Arrays.asList(a);
http://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#asList(T...)
It would depend on your definition of "quickest", but in both cases this would be it.
List list = Arrays.asList(array);
Collections.addAll(list, array);
One of the first google link :
http://javarevisited.blogspot.com/2011/06/converting-array-to-arraylist-in-java.html
Use Google's Guava APIs, using collections is so much simpler.
String[] a = {"Test1", "test2"};
List<String> l = Lists.newArrayList(a);
Arrays.asList() works for your example of String[], but if your're converting a primitive array, such as int[] or double[], then this will produce a single item list of the array. A good solution is to use Google Guava's primitive helper classes, such as Ints:
int[] a = new int[]{1,2,3};
List<Integer> l = Ints.asList(a);
For a more detailed explanation, see this answer.
int[] alist = new int [3];
alist.add("apple");
alist.add("banana");
alist.add("orange");
Say that I want to use the second item in the ArrayList. What is the coding in order to get the following output?
output:
banana
You have ArrayList all wrong,
You can't have an integer array and assign a string value.
You cannot do a add() method in an array
Rather do this:
List<String> alist = new ArrayList<String>();
alist.add("apple");
alist.add("banana");
alist.add("orange");
String value = alist.get(1); //returns the 2nd item from list, in this case "banana"
Indexing is counted from 0 to N-1 where N is size() of list.
Read more about Array and ArrayList
List<String> aList = new ArrayList<String>();
aList.add("apple");
aList.add("banana");
aList.add("orange");
String result = alist.get(1); //this will retrieve banana
Note: Index starts from 0 i.e. Zero
Resource
Using an Array:
String[] fruits = new String[3]; // make a 3 element array
fruits[0]="apple";
fruits[1]="banana";
fruits[2]="orange";
System.out.println(fruits[1]); // output the second element
Using a List
ArrayList<String> fruits = new ArrayList<String>();
fruits.add("apple");
fruits.add("banana");
fruits.add("orange");
System.out.println(fruits.get(1));
Exactly as arrays in all C-like languages. The indexes start from 0. So, apple is 0, banana is 1, orange is 2 etc.
In order to store Strings in an dynamic array (add-method) you can't define it as an array of integers ( int[3] ). You should declare it like this:
ArrayList<String> alist = new ArrayList<String>();
alist.add("apple");
alist.add("banana");
alist.add("orange");
System.out.println( alist.get(1) );
The big difference between primitive arrays & object-based collections (e.g., ArrayList) is that the latter can grow (or shrink) dynamically. Primitive arrays are fixed in size: Once you create them, their size doesn't change (though the contents can).
Here is how I would write it.
String[] fruit = "apple banana orange".split(" ");
System.out.println(fruit[1]);