retrieve values from arraylist of hashmap in java? - java

I've a hashmap as shown below.
indexMap = new HashMap<String, ArrayList<Integer>>();
I could collect values from string like this,
String[] keysProblem2 = (String[]) indexMap.keySet().toArray(new String[0]);
How to collect values from arraylist? I tried doing like this,
Integer [] valuesProblem2 = (Integer[]) indexMap.values().toArray(new Integer[indexMap.size()]);
but was given an error like this,
java.lang.ArrayStoreException: java.lang.String
at java.util.AbstractCollection.toArray(Unknown Source)

indexMap.values() returns a Collection of ArrayList<Integer>s. You can't call .toArray(new Integer[indexMap.size()]) because it's a collection of ArrayList<Integer>, not Integers.
If you want to iterate through all ArrayLists, and create one large Integer[], then you'd have to do something like this:
ArrayList<ArrayList<Integer>> arrays = new ArrayList<ArrayList<Integer>>(indexMap.values());
ArrayList<Integer> allInts = new ArrayList<Integer>();
for(ArrayList<Integer> ints : arrays) {
allInts.addAll(ints);
}
Integer[] valuesProblem2 = (Integer[])allInts.toArray(new Integer[0]);

Related

java - "int cannot be converted to ArrayList"

I'm trying to create a two dimensional ArrayList which will store ints, strings & booleans.
I've got as far as entering the first int, but I get a red squiggle and the error "int cannot be converted to ArrayList".
ArrayList[][] qarray= new ArrayList [10][5];
qarray[0][0]= 1;
BTW, googling the phrase "int cannot be converted to ArrayList" is giving me exactly six results.
The error is correct.
Your array type is ArrayList. You can insert only ArrayLists in that array.
If you want to store int's, your declaration should be.
int[][] qarray= new int [10][5];
And also, as someone commented, you cannot store strings and booleans in this array anymore.
ArrayList[][] qarray= new ArrayList [10][5];
Basically your code creates 2 dimensional array list objects (50 array list objects).
qarray[0][0]= 1;
And you are trying to assign integer, where you need to create a ArrayList object. It expects something like
qarray[0][0]= new ArrayList();
However this would not meet your objective. The following piece of code could meet your objectives:
ArrayList[] qarray = new ArrayList[10];
qarray[0]= new ArrayList();
qarray[0].add(1);
qarray[1]= new ArrayList();
qarray[1].add(true);
qarray[2]= new ArrayList();
qarray[2].add("hello");
Try like this:
List<Integer> qarray = new ArrayList<>();
qarray.add(1);
First I believe that you need array and not ArrayList. 2d array can be created as following.
int[][] arr = new int [10][10];
Your next problem is that you tried to assign int constant 1 to variable of other type. The following example shows how to assign int to element of array
arr [0][0] = 1;
According to javadoc, you can not create arrays of ArrayList. Use 2D array instead.
If you need 2D ArrayList anyway, you should have tried this way:
ArrayList<ArrayList<Integer>> listOfLists = new ArrayList<>();
ArrayList<Integer> list1 = new ArrayList<>();
list1.add(1);
list1.add(2);
ArrayList<Integer> list2 = new ArrayList<>();
list2.add(5);
listOfLists.add(list1);
listOfLists.add(list2);
ArrayList<Integer> list = new ArrayList<>();
list.add(1);
you wan to add int,String and boolean then you can use
ArrayList<ArrayList<Object>> listOfLists = new ArrayList<ArrayList<Object>>();
it will help you
ArrayList<Integer>[][] list = new ArrayList[10][10];
list[0][0] = new ArrayList<>();
list[0][0].add(new Integer(10);
try like this.

Convert nested list to 2d array

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);

Java ArrayList for integers

I have values that I'd like to add into an ArrayList to keep track of what numbers have shown up.
The values are integers so I created an ArrayList;
ArrayList<Integer[]> list = new ArrayList<>();
int x = 5
list.add(x);
But I'm unable to add anything to the ArrayList using this method.
It works if I use Strings for the array list. Would I have to make it a String array and then somehow convert the array to integers?
EDIT: I have another question. I'd like the list to only hold 3 values. How would I do so?
List of Integer.
List<Integer> list = new ArrayList<>();
int x = 5;
list.add(x);
You are trying to add an integer into an ArrayList that takes an array of integers Integer[]. It should be
ArrayList<Integer> list = new ArrayList<>();
or better
List<Integer> list = new ArrayList<>();
you are not creating an arraylist for integers, but you are trying to create an arraylist for arrays of integers.
so if you want your code to work just put.
List<Integer> list = new ArrayList<>();
int x = 5;
list.add(x);
you should not use Integer[] array inside the list as arraylist itself is a kind of array. Just leave the [] and it should work
Actually what u did is also not wrong your declaration is right . With your declaration JVM will create a ArrayList of integer arrays i.e each entry in arraylist correspond to an integer array hence your add function should pass a integer array as a parameter.
For Ex:
list.add(new Integer[3]);
In this way first entry of ArrayList is an integer array which can hold at max 3 values.
The [] makes no sense in the moment of making an ArrayList of Integers because I imagine you just want to add Integer values.
Just use
List<Integer> list = new ArrayList<>();
to create the ArrayList and it will work.
Here there are two different concepts that are merged togather in your question.
First : Add Integer array into List. Code is as follows.
List<Integer[]> list = new ArrayList<>();
Integer[] intArray1 = new Integer[] {2, 4};
Integer[] intArray2 = new Integer[] {2, 5};
Integer[] intArray3 = new Integer[] {3, 3};
Collections.addAll(list, intArray1, intArray2, intArray3);
Second : Add integer value in list.
List<Integer> list = new ArrayList<>();
int x = 5
list.add(x);
How about creating an ArrayList of a set amount of Integers?
The below method returns an ArrayList of a set amount of Integers.
public static ArrayList<Integer> createRandomList(int sizeParameter)
{
// An ArrayList that method returns
ArrayList<Integer> setIntegerList = new ArrayList<Integer>(sizeParameter);
// Random Object helper
Random randomHelper = new Random();
for (int x = 0; x < sizeParameter; x++)
{
setIntegerList.add(randomHelper.nextInt());
} // End of the for loop
return setIntegerList;
}

Java Array and ArrayList

When I try to create an ArrayList myArrayList from an array, using Arrays.asList(myArray), I am not getting the List of elements in myArray. Instead I get list of Array.
The size of myArrayList is 1 . When I try to do myArrayList.toArray(), I am getting a two dimensional array. What to do to get the elements of myArray in a list? Is iterating the only option??
Firstly, the asList method is the right method:
Integer[] myArray = new Integer[3];
List<Integer> myArrayList = Arrays.asList(myArray);
System.out.println(myArrayList.size()); // prints 3, as expected
The problem may be that you are calling the varargs asList method in such a way that java is interpreting your parameter as the first varargs value (and not as an array of values).
Object myArray = new Integer[3];
List<Object> myArrayList = Arrays.asList(myArray);
System.out.println(myArrayList.size()); // prints 1 - java invoked it as an array of Integer[]
To fix this problem, try casting your parameter as Object[] to force the varargs invocation, eg:
Object myArray = new Integer[3];
List<Object> myArrayList = Arrays.asList((Object[]) myArray); // Note cast here
System.out.println(myArrayList.size()); // prints 3, as desired
What is the type of myArray? You cannot use Arrays.asList with an array of primitive type (such as int[]). You need to use loop in that case.
There are different ways by which you can achieve it.3 example of converting array to arraylist and arraylist to array in java might help.
Would this work?
Object[] myArray = new Object[4]; //change this to whatever object you have
ArrayList<Object> list = new ArrayList<Object>();
for (Object thing : myArray) list.add(thing);
Try providing the generic type in the method call. The following gives me a list of 2 String elements.
String[] strings = new String[]{"1", "2"};
List<String> list = Arrays.<String>asList(strings);
System.out.println(list.size());

List Arrary Double[] entering values

Using the examples below the 2nd part I see how to add values to a single dim array. But the 2 dim array I dont yet understand. In the 1st example the 1,2,3 I need to get from a database. The DB part I have figured out but how to put in the values I dont know.
If I was using an array it would be
myarray[row][column] = value;
so how do I do this with the List?
mylist.add --- something?
List<double []> // creates a list that stores arrays of doubles.
List<double []> myList = new ArrayList<Double>();
myList.add(new double [] {1,2,3});
myList.add(new double [] {4,5,6});
List<Double> myList = new ArrayList<Double>();
myList.add(1);
myList.add(2);
myList.add(3);
You should avoid using arrays as generic type parameters as you can easily end up with "unchecked" warnings. Use collections (typically ArrayList) instead.
So instead of this:
List<double []> // creates a list that stores arrays of doubles.
List<double []> myList = new ArrayList<Double>();
myList.add(new double [] {1,2,3});
myList.add(new double [] {4,5,6});
Do something like this:
List<List<Double>> myList = new ArrayList<List<Double>>();
myList.add(new ArrayList<Double>());
myList.add(new ArrayList<Double>());
myList.get(0).add(1);
myList.get(0).add(2);
myList.get(0).add(3);
Or to initialize together, you'd probably do something like:
List<List<Double>> myList = new ArrayList<List<Double>>();
List<Double> nested;
nested = new ArrayList<Double>();
nested.add(1);
nested.add(2);
nested.add(3);
myList.add(nested);
nested = new ArrayList<Double>();
nested.add(4);
nested.add(5);
nested.add(6);
myList.add(nested);
(You can add nested to myList before or after adding the elements to nested -- either way works so do whatever is clearer to you.)
To retrieve a specific element:
double value = myList.get(x).get(y);
To set a specific element:
myList.get(x).set(y, value);
This assumes that the list are already the right size, and that you just want to change the value of an existing element. (In other words, just like set behaves on a simple List.)
If you're talking about just doing inline initialization of a multidimensional array, I'm pretty sure you just use subsetted braces, like so:
Double array2D[][] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
Do you want a collection-based solution for two-dimensional arrays? If so, then you're looking for a list of lists.
//Declaration
List<List<double[]>> twoDimList = new ArrayList<List<double>>();
//Adding values
twoDimList.add(new ArrayList<double>(1));
twoDimList.add(new ArrayList<double>(2));
twoDimList.add(new ArrayList<double>(3));
//Retrieving values
double value = twoDimList.get(1).get(1); //returns 1
List<T> myList = new ArrayList<T>();
T should be same. If T is double[] then it should be new ArrayList<double[]>()
then get(index) which is double array and get(index)[j] which is value. same logic with
d[i][j] = get(index)[j]
List<double []> myList = new ArrayList<double[]>();
myList.add(new double [] {1,2,3});
myList.add(new double [] {4,5,6});
System.out.println(myList.get(0)[1]);

Categories