Convert ArrayList to Double Array in java [duplicate] - java

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]

Related

error: incompatible types: List<Integer> cannot be converted to ArrayList<Integer>

I have found a few questions similar to the problem I am facing, but I couldn't find solution.
Example: Incompatible types List of List and ArrayList of ArrayList, Not able to understand how to define a List of List in java
The program should return list of lists. So, I declared a list of lists and then trying to add arraylists to it.
allsubsets = new ArrayList<List<Integer>>();
But, when I am trying to access each arraylist item from the list of lists as below, I get the error: incompatible types: List<Integer> cannot be converted to ArrayList<Integer>
for(ArrayList<Integer> subset:allsubsets)
When I try to convert the line to for(List<Integer> subset:allsubsets), it throws error that add, addAll don't exist for List type, which makes sense. Please help me understand how to access elements of list of lists in this case.
public List<List<Integer>> subsets(int[] nums) {
List<Integer> arrayList = new ArrayList<Integer>();
for(int i:nums) {
arrayList.add(i);
}
return subsets(arrayList,nums.length);
}
public List<List<Integer>> subsets(List<Integer> arrayList, int index) {
List<List<Integer>> allsubsets;
if(index == -1) {
allsubsets = new ArrayList<List<Integer>>();
allsubsets.add(new ArrayList<Integer>());
}
else {
allsubsets = subsets(arrayList, index-1);
int item = arrayList.get(index);
List<List<Integer>> moresubsets = new ArrayList<List<Integer>>();
for(ArrayList<Integer> subset:allsubsets) {
//The line above throws error as I created list of lists
List<Integer> newsubset = new ArrayList<Integer>(); //create new subset
newsubset.addAll(subset); // add all old items
newsubset.add(item); // add new item
moresubsets.add(newsubset); //add subset to moresubsets
}
allsubsets.add(moresubsets); // add to actual one
}
return allsubsets;
}
Note: If I change the return type to arraylist of arraylists, it works for me. But, I want to make it work for the list of lists
Correct way to iterate your list of list should be:
for(List<Integer> subset:allsubsets) {
instead of:
for(ArrayList<Integer> subset:allsubsets) {
List<List<Integer>> allsubsets is declared as List of List, but the implementation is unknown.
Only you know the type of nested List is ArrayList, so either change foreach to use List<Integer> or manually cast your List<Integer> to ArrayList<> (this is not preferred)
One more thing:
allsubsets.add(moresubsets); // add to actual one
This try to add a List of List (List<List<Integer>>) as element which should be List<Integer> hence compile error.
Change that statement to:
allsubsets.addAll(moresubsets);
Let's try expanding that enhanced for loop into more basic components:
for(ArrayList<Integer> subset:allsubsets) {
//The line above throws error as I created list of lists
}
// this is roughly equivalent to
Iterator<List<Integer>> it = allsubsets.iterator();
while(it.hasNext()) {
ArrayList<Integer> subset = it.next(); // Error
// Since the iterator was defined as an iterator to a List<List<Integer>>,
// it.next() will return the next element in allsubsets
// which happens to be an List<Integers>.
// You can't assign a reference of a parent type to a child. However
// the opposite is perfectly fine, assigning a reference of a child type
// to a parent.
// If we change subset to be a List<Integer> i.e.
// for(List<Integer> subset : allsubsets)
// then we are assigning a reference of a List<Integer> to a List<Integer>
// so no problem.
}
I prefer to share with you the code I did for managing the same type of Object List you are trying to handle. Hope this helps.
public static void main(String[] args) {
List<List<Integer>> allsubsets = setSubsets();
List<List<Integer>> allsubsets2 = new ArrayList<>();
allsubsets2.addAll(allsubsets);
int i= 0;
for (List<Integer> test : allsubsets2) {
System.out.println(i + " Lista");
for (Integer integer : test) {
System.out.println(integer);
}
i++;
}
}
public static List<List<Integer>> setSubsets() {
List<List<Integer>> allsubsets = new ArrayList<List<Integer>>();
List<Integer> listInteger1 = new ArrayList<>();
List<Integer> listInteger2 = new ArrayList<>();
for (int i = 0; i < 100; i++) {
listInteger1.add(i);
}
for (int i = 1010; i < 1110; i++) {
listInteger2.add(i);
}
allsubsets.add(listInteger1);
allsubsets.add(listInteger2);
return allsubsets;
}

Converting Array of int to ArrayList and vice versa [duplicate]

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

Flatten nested arrays. (Java)

I'm struggling to create the right logic to flatten an array. I essentially want to duplicate parent rows for each child item in a nested array. The number of nested arrays could vary. I've been creating Java lists bc I find them easy to work with, but open to any solution. The nature of this problem is I'm starting with some nested JSON that I want to convert into a flat csv to load into a database table. Thanks for the help.
Example:
[1,2,[A,B,[Cat,Dog]],3]
I've created the above as a List. Each item is either a string or another List.
Result:
[1,2,A,Cat,3],
[1,2,A,Dog,3],
[1,2,B,Cat,3],
[1,2,B,Dog,3]
Here's what I have so far. Obviously not working.
private static List<List<String>> processData(List<String> row, List<Object> data, List<List<String>> rowList) {
List<List<String>> tempRowList = new ArrayList<List<String>>();
for (Object i : data) {
if (i instanceof List<?>) {
flattenArray((List<Object>) i, row, rowList);
} else {
for (List<String> r : rowList) {
r.add(i.toString()); //add item to all rows
}
}
}
return rowList;
private static void flattenArray(List<Object> arrayObject, List<String> rowToCopy, List<List<String>> rowList) {
for (Object x : arrayObject) {
if (x instanceof List<?>) {
for (List<String> t : rowList) {
flattenArray((List<Object>) x, t, rowList);
}
} else {
List<String> newRow = new ArrayList<String>(rowToCopy); //copy row
List<Object> t = new ArrayList<Object>();
t.add(x);
List<List<String>> innerRowList = new ArrayList<List<String>>();
innerRowList.add(newRow);
processData(newRow, t, innerRowList); //pass in new copied row. object to add,
rowList.add(newRow);
}
}
rowList.remove(rowToCopy);
}
And i set everything up like this.
public static void main(String[] args) {
List<Object> data = new ArrayList<Object>();
List<List<String>> rowList = new ArrayList<List<String>>();
data.add("1");
data.add("2");
List<Object> l1 = new ArrayList<Object>();
l1.add("A");
l1.add("B");
List<Object> l2 = new ArrayList<Object>();
l2.add("dog");
l2.add("cat");
l1.add(l2);
data.add(l1);
data.add("3");
List<String> r0 = new ArrayList<String>();
rowList.add(r0);
System.out.println(data);
rowList = processData(r0, data, rowList);
System.out.println(rowList);
}
I think this should work for you if you're using Java 8:
List<Object> a = new ArrayList<>();
List<Object> a1 = new ArrayList<>();
a1.add("v");
a1.add("w");
List<Object> a2 = new ArrayList<>();
a2.add("ww");
a.add("a");
a.add("b");
a.add("c");
a.add("d");
a.add(a1);
a.add(a2);
List<Object> b = new ArrayList<>();
a.stream().flatMap(x -> x instanceof String ? Stream.of(x) : ((List) x).stream()).forEach(b::add);
System.out.println(a);
System.out.println(b);
b list will contain flattened a list. Output is:
[a, b, c, d, [v, w], [ww]]
[a, b, c, d, v, w, ww]

How to convert from ArrayList<Double> to double[] [duplicate]

This question already has answers here:
How to convert an ArrayList containing Integers to primitive int array?
(19 answers)
Closed 7 years ago.
Does anyone know how to pass a double arraylist into another method? (I have highlighted it)I get this message from compiler : cannot convert from ArrayList to double[]
ArrayList<Double> value = new ArrayList<Double>();
while (rs.next())
{
ArrayList<Integer> r=new ArrayList<Integer>();
r.add(rs.getInt("Type"));
r.add(rs.getInt("Budget"));
r.add(rs.getInt("Day"));
r.add(rs.getInt("Preferences"));
int vec2[] = r.stream().mapToInt(t -> t).toArray();
double cos_sim=cosine_similarity(vec1,vec2);
value.add(cos_sim);
}
pick_highest_value_here_and_display(value);
ps.close();
rs.close();
conn.close();
}
private void pick_highest_value_here_and_display(ArrayList<Double> value) {
// TODO Auto-generated method stub
**double aa[]=value ;**
double highest=aa[0];
for(int i=0;i<aa.length;i++)
{
if(aa[i]>highest){
highest=aa[i];
}
}
System.out.println(highest);
}
You can use Java8 in a same way you used it for int[]
ArrayList<Double> value = new ArrayList<Double>();
double[] arr = value.stream().mapToDouble(v -> v.doubleValue()).toArray();
OR (As per below comment of yshavit)
double[] arr = value.stream().mapToDouble(Double::doubleValue).toArray();
You can copy all the element to a double[] by copying one at a time, but you don't need to.
List<Double> value = Arrays.asList(1.1, 3.3, 2.2);
Optional<Double> max = value.stream().max(Comparator.<Double>naturalOrder());
System.out.println(max.get());
prints
3.3
If you can change to Double[] then you can do like :-
Double[] doubleArr= value.toArray(new Double[value.size()]);
Else if you want double[], then you can do like :-
double[] doubleArr= new double[value.size()];
int index = 0;
for(double i : value){
doubleArr[index] = i; // unboxing is automtically done here
index++;
}
Here is a working solution:
ArrayList<Double> a = new ArrayList<Double>();
a.add(0.23);
a.add(2.4);
Double[] b = new Double[a.size()];
b = a.toArray(b);
for (int i = 0; i < b.length; i++) {
System.out.println(b[i]);
}

list of 2D array in java

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

Categories

Resources