i have set of 2D arrays and i want store all 2D arrays into single list how can do this in java?
Can't you just pass the set into a list like so:
int [][]a = new int[3][3];
Set<int[][]> set = new HashSet<int[][]>();
set.add(a);
ArrayList<int[][]> list = new ArrayList<int[][]>(set);
Or am I not understanding your question.
List<String[][]> myFunc( Set<String[][]> s ) {
List<String[][]> l = new ArrayList<String[][]>( s.length() );
l.addAll( s );
return l;
}
e.g. or what do you mean
int[][] a2d = new int[15][15];
int[][] b2d = new int[10][10];
List<int[][]> list2d = new ArrayList<int[][]>(10);
list2d.add(a2d);
list2d.add(b2d);
or do you mean you have a Set<int[][]> then you can simply do what tpierzina suggested
List<int[][]> list2d = new ArrayList<int[][]>();
list2d.addAll(nameOfYourSetVariable);
or
List<int[][]> list2d = new ArrayList<int[][]>(nameOfYourSetVariable);
Related
'''
String array[] = new String[]{"ash","String","Ukara"};
int [] ar = new int[]{1,2,3,4};
Object i[][] = {array,ar};
'''
On adding int array to array of array showing this error as --> Type mismatch: cannot convert from int[] to Object[]
You could create an Object[][] with Object[] and Integer[] as follows:
Object[] arr1 = new Object[3];
Integer[] arr2 = new Integer[3];
Object[][] arr3 = {arr1, arr2};
Alternatively, other approaches such as a HashMap<String, Integer> or a new class might work better for your use case.
You could create a new class such as the following:
public class SomeClass {
private String var1;
private int var2;
}
Then create an array of this type:
SomeClass[] array = new SomeClass[3];
So the issue I'm having is after copying the 2d arraylist, changing the element from one 2d arraylist affects the other 2d arraylist. I want them to be completely separate in memory.
First example shows how it works correctly with 1d arraylists...
import java.util.ArrayList;
public class QuickTest {
public static void main(String[] args) {
ArrayList<Integer> firstList = new ArrayList<>();
ArrayList<Integer> secondList = new ArrayList<>();
Integer counter = 2;
for(int arrI = 0; arrI < 4; arrI++, counter+=2){
firstList.add(counter);
}
secondList = new ArrayList<>(firstList);
System.out.println("firstList.get(2) = " + firstList.get(2));
System.out.println("secondList.get(2) = " + secondList.get(2));
firstList.set(2, 7);
System.out.println("firstList.get(2) = " + firstList.get(2));
System.out.println("secondList.get(2) = " + secondList.get(2));
}
}
Expected output:
Notice how the element from the first arraylist is changed but not the second arraylist element is not changed. This is good and what we want.
Now to try and copy the 2d arraylists...
import java.util.ArrayList;
public class QuickTest {
public static void main(String[] args) {
ArrayList<ArrayList<Integer>> firstTwoDimList = new ArrayList<>();
ArrayList<ArrayList<Integer>> secondTwoDimList = new ArrayList<>();
firstTwoDimList.add(new ArrayList<Integer>());
firstTwoDimList.add(new ArrayList<Integer>());
firstTwoDimList.add(new ArrayList<Integer>());
Integer counter = 2;
for(int arrI = 0; arrI < firstTwoDimList.size(); arrI++, counter+=2){
firstTwoDimList.get(arrI).add(counter);
counter+=2;
firstTwoDimList.get(arrI).add(counter);
}
secondTwoDimList = new ArrayList<>(firstTwoDimList);
System.out.println("firstTwoDimList.get(1).get(0) = " + firstTwoDimList.get(1).get(0));
System.out.println("secondTwoDimList.get(1).get(0) = " + secondTwoDimList.get(1).get(0));
firstTwoDimList.get(1).set(0, 7);
System.out.println("firstTwoDimList.get(1).get(0) = " + firstTwoDimList.get(1).get(0));
System.out.println("secondTwoDimList.get(1).get(0) = " + secondTwoDimList.get(1).get(0));
}
}
Unexpected output:
Anyone have any idea what the reason for this is, and what the best solution would be?
This is what is happening in the 1D array list case, in terms of references:
This is what is happening in the 2D array list case:
This means that when you copy an array list using this:
new ArrayList<>(someOldArrayList)
the items themselves don't get copied, only a new array list object is created, referring to all the items in the old array list.
In the second case, you are only changing what array list 2's items are, but index 1 of first list and second list refers to the same array list 2.
To fix this, you need to copy the array lists inside first list and second list as well. One way to do this:
secondList = new ArrayList<>(firstList.stream().map(x -> new ArrayList<>(x)).collect(Collectors.toList()));
You should iterate through the size of the first dimension of the firstTwoDimArray and add new reference of each second dimension to the secondTwoDimArray. i.e.
for(int index = 0; index < firstTwoDimList.size(); index++) {
secondTwoDimList.add(new ArrayList<Integer>(firstTwoDimList.get(index)));
}
The difference between your first and second example is that in the second one you use get(). This get() returns a new variable, so you assign the integers to it and not to the original ArrayList.
If you want to assign a value:
firstTwoDimList.set(1, new ArrayList<Integer>(Arrays.asList(0, 7)));
I guess I was looking for something like this...
import java.util.ArrayList;
public class QuickTest {
public static ArrayList<ArrayList<Integer>> getTwoDimArrListCopy(ArrayList<ArrayList<Integer>> original){
ArrayList<ArrayList<Integer>> copy = new ArrayList<>();
for (ArrayList<Integer> arr: original){
copy.add(new ArrayList<Integer>(arr));
}
return copy;
}
public static void main(String[] args) {
ArrayList<ArrayList<Integer>> firstTwoDimList = new ArrayList<>();
ArrayList<ArrayList<Integer>> secondTwoDimList = new ArrayList<>();
firstTwoDimList.add(new ArrayList<Integer>());
firstTwoDimList.add(new ArrayList<Integer>());
firstTwoDimList.add(new ArrayList<Integer>());
Integer counter = 2;
for(int arrI = 0; arrI < firstTwoDimList.size(); arrI++, counter+=2){
firstTwoDimList.get(arrI).add(counter);
counter+=2;
firstTwoDimList.get(arrI).add(counter);
}
secondTwoDimList = getTwoDimArrListCopy(firstTwoDimList);
System.out.println("firstTwoDimList.get(1).get(0) = " + firstTwoDimList.get(1).get(0));
System.out.println("secondTwoDimList.get(1).get(0) = " + secondTwoDimList.get(1).get(0));
firstTwoDimList.get(1).set(0, 7);
System.out.println("firstTwoDimList.get(1).get(0) = " + firstTwoDimList.get(1).get(0));
System.out.println("secondTwoDimList.get(1).get(0) = " + secondTwoDimList.get(1).get(0));
}
}
I was just hoping there was a built in library that would do that getTwoDimArrListCopy() function for me...
This question already has answers here:
How to cast from List<Double> to double[] in Java?
(7 answers)
Closed 5 years ago.
How to Convert ArrayList to Double Array in Java6?
List lst = new ArrayList();
double[] dbl=null;
lst.add(343.34);
lst.add(432.34);
How convert above list to array?
You can directly convert the List to an Array of the wrapper class.
Try the following:
List<Double> lst = new ArrayList<>();
Double[] dblArray = new Double[lst.size()];
lst.add(343.34);
lst.add(432.34);
dblArray = lst.toArray(dblArray);
List<Number> lst = new ArrayList<>();
Collections.addAll(lst, 3.14, -42);
double[] dbl = lst.stream()
.map(Number::cast) // Or possibly Double::cast when List lst.
.mapToDouble(Number::doubleValue)
.toArray();
List<Double> lst = new ArrayList<>();
Collections.addAll(lst, 3.14, -42.0);
double[] dbl = lst.stream()
.mapToDouble(Double::doubleValue)
.toArray();
The mapToDouble transforms an Object holding Stream to a DoubleStream of primitive doubles.
With this you will make the list and add what you like. Then make the array the same size and fill front to back.
public static void main(String[] args){
List lst = new ArrayList();
lst.add(343.34);
lst.add(432.34);
System.out.println("LST " + lst);
double[] dbl= new double[lst.size()];
int iter = 0;
for (Object d: lst
) {
double e = (double) d;
dbl[iter++] = e;
}
System.out.println("DBL " + Arrays.toString(dbl));
}
Result: LST [343.34,432.34] DBL [343.34,432.34]
This question already has answers here:
Convert an array of primitive longs into a List of Longs
(17 answers)
Closed 5 years ago.
I have an array int[] a = {1,2,3} I want to convert it to an ArrayList, and vice versa. These are my attempts but they don't work. Can someone point me in the right direction, please.
The following are my attempts below
public class ALToArray_ArrayToAL {
public static void main(String[] args) {
ALToArray_ArrayToAL obj = new ALToArray_ArrayToAL();
obj.populateALUsingArray();
}
public void populateArrayUsingAL()
{
ArrayList<Integer> al = new ArrayList<>();
al.add(1);al.add(2);al.add(3);al.add(4);
/* Don't want to do the following, is there a better way */
int[] a = new int[al.size()];
for(int i = 0;i<al.size();i++)
a[i] = al.get(i);
/* This does not work either */
int[] b = al.toArray(new int[al.size()]);
}
public void populateALUsingArray()
{
/* This does not work, and results in a compile time error */
int[] a = {1,2,3};
ArrayList<Integer> al = new ArrayList<>(Arrays.asList(a));
/* Does not work because I want an array of ints, not int[] */
int[] b = {4,5,6};
List list = new ArrayList(Arrays.asList(b));
for(int i = 0;i<list.size();i++)
System.out.print(list.get(i) + " ");
}
}
Accept the inevitability of a for loop:
for (int i : array) {
list.add(i);
}
...or use streams in Java 8, though frankly they're more of a pain than they're worth for this case:
Arrays.stream(array).boxed().collect(Collectors.toList())
...or use a third-party library like Guava and write
List<Integer> list = Ints.asList(array);
I am trying to randomly generate 'n' number of items from a HashMap where 'n' is determined by the user.
Here is what I have so far:
public static void main(String []args){
int numColors = 3;
HashMap<String, String> map = new HashMap<String, String>();
map.put("White","FFFFFF");
map.put("Blank","000000");
map.put("Red","ED0A15");
map.put("Green","06F76C");
map.put("Blue","0689FF");
map.put("Sky Blue","00C2FC");
map.put("Light Blue","08F0FC");
map.put("Silver","C0BFC5");
map.put("Mint","ABD3CA");
map.put("Off White","FFEFF0");
map.put("Purple","736FFA");
map.put("Lavendar","DEBEEF");
map.put("Hot Pink","F5159A");
map.put("Pink","DB39CC");
map.put("Light Pink","F5C2E3");
map.put("Blush","C95FA7");
map.put("Orange","D4361B");
map.put("Yellow","DEF231");
map.put("Warm White","F3E4C3");
map.put("Turquoise","01DCA4");
List<String> valuesList = new ArrayList<String>(map.values());
int randomIndex = new Random().nextInt(valuesList.size());
String randomValue = valuesList.get(randomIndex);
System.out.printf(randomValue);
}
It prints 1 random color for me (in hex) which I want, however I am unsure of how/which loop to use in order to generate say 3 random hex colors from the map. I declared numColors as 3 just to try and test this out.
Here is what I ended up going with:
public static void main(String []args){
int numColors = 3;
HashMap<String, String> map = new HashMap<String, String>();
map.put("White","FFFFFF");
map.put("Blank","000000");
map.put("Red","ED0A15");
map.put("Green","06F76C");
map.put("Blue","0689FF");
map.put("Sky Blue","00C2FC");
map.put("Light Blue","08F0FC");
map.put("Silver","C0BFC5");
map.put("Mint","ABD3CA");
map.put("Off White","FFEFF0");
map.put("Purple","736FFA");
map.put("Lavendar","DEBEEF");
map.put("Hot Pink","F5159A");
map.put("Pink","DB39CC");
map.put("Light Pink","F5C2E3");
map.put("Blush","C95FA7");
map.put("Orange","D4361B");
map.put("Yellow","DEF231");
map.put("Warm White","F3E4C3");
map.put("Turquoise","01DCA4");
List<String> keys = new ArrayList<String>(map.keySet());
Random rand = new Random();
for (int i = 0; i < numColors; i++) {
String key = keys.get(rand.nextInt(keys.size()));
System.out.println(map.get(key));
}
}
A simple solution is to shuffle the entire map using Collections.shuffle(map). Then just iterating over it and picking the first n elements.
Of course this doesn't make sense if the map is huge and you only need a couple of elements.
Edit:
Naturally, with this solution you won't get any duplicate entries
If I understand your question, you could do it with
List<String> keys = new ArrayList<String>(map.keySet());
Random rand = new Random();
for (int i = 0; i < numColors; i++) {
String key = keys.get(rand.nextInt(keys.size()));
System.out.println(map.get(key));
}
Changes are mentioned in comments
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int numColors = 3;
HashMap<String, String> map = new HashMap<String, String>();
map.put("White", "FFFFFF");
map.put("Blank", "000000");
map.put("Red", "ED0A15");
map.put("Green", "06F76C");
map.put("Blue", "0689FF");
map.put("Sky Blue", "00C2FC");
map.put("Light Blue", "08F0FC");
map.put("Silver", "C0BFC5");
map.put("Mint", "ABD3CA");
map.put("Off White", "FFEFF0");
map.put("Purple", "736FFA");
map.put("Lavendar", "DEBEEF");
map.put("Hot Pink", "F5159A");
map.put("Pink", "DB39CC");
map.put("Light Pink", "F5C2E3");
map.put("Blush", "C95FA7");
map.put("Orange", "D4361B");
map.put("Yellow", "DEF231");
map.put("Warm White", "F3E4C3");
map.put("Turquoise", "01DCA4");
// scanner for accepting values
Scanner scan = new Scanner(System.in);
System.out.println("Enter number");
int N = scan.nextInt();
// random object for generating random values
Random rand = new Random();
// converting map values to list
List<String> valuesList = new ArrayList<String>(map.values());
for (int i = 1; i <= N; i++) {
// choose random value
int randomIndex = rand.nextInt(valuesList.size());
// get value
String randomValue = valuesList.get(randomIndex);
// printing
System.out.println("Random value " + i + " : " + randomValue);
}
}
}
To prevent duplicates you can do something like this :
// random object for generating random values
Random rand = new Random();
// converting map values to list
List<String> valuesList = new ArrayList<String>(map.values());
Set<String> set = new HashSet<String>();
while (set.size() != N) {
int randomIndex = rand.nextInt(valuesList.size());
String randomValue = valuesList.get(randomIndex);
set.add(randomValue);
}
System.out.println(set);
As Malt suggested, to prevent duplicates and keep code clean:
List<String> list = new ArrayList(map.values() );
Collections.shuffle(list);