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]);
}
Related
I created 4 arrays to store employee-data (ID, Name, Age, Salary).
String[] empID = new String[arrayLength];
String[] empName = new String[arrayLength];
int[] empAge = new int[arrayLength];
double[] empPay = new double[arraylength];
I sorted the salary arrays in ascending order.
Arrays.sort(empPay);
I want the index of the elements in the sorted array (empPay) against the original array (tempPay) similar to the code below.
double[] price = {12,4,65.89,33.5,24,90};
double[] pr = {4,12,24,33.5,65.89,90};
int[] pos = new int[6];
int prCount = 0;
do {
for (int i=0;i<price.length;i++) {
if (pr[prCount] == price[i]) {
pos[prCount] = i;
prCount++;
}
}
} while (prCount<pr.length);
System.out.println(Arrays.toString(pos));
When I apply this logic to my code, I get an "IndexOutOfBoundException"
...
inPay = scanner.nextDouble();
for (...) {
empPay[count] = inPay;
tempPay[count] = inPay;
}
Arrays.sort(empPay);
int[] index = new int[arrayLength];
int listCount = 0;
do {
for (int j=0;j<tempPay.length;j++) {
if (empPay[listCount] == tempPay[j]) {
index[listCount] = j;
listCount++;
}
}
} while (listCount<empPay.length);
System.out.println(Arrays.toString(index));
Why does the logic work in the first code and not the second. I want to display all employee information properly aligned.
Please, Kindly avoid objects or collections or other sophisticated approach to the problem. I teach Grade 9 kids.
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);
how do i store the result of "week_result" i calculate into an array
public double calculation() {
`week_result = round(((inWatts/100)*use_hours*3600/1000)*0.54,2);
Toast.makeText(getApplicationContext(),
"weekly : " + week_result, Toast.LENGTH_LONG).show();
return week_result;
}
public static double round(double value, int places) {
if (places < 0) throw new IllegalArgumentException();
BigDecimal bd = new BigDecimal(value);
bd = bd.setScale(places, RoundingMode.HALF_UP);
return bd.doubleValue();
}
}
and how can i add up all the values stored in this array in another class ....
Use an ArrayList as it will increase in size as and when more space is needed
ArrayList<Double> results = new ArrayList<Double>();
Add a result to the list using
results.add(result);
When you want to find the sum of the ArrayList use a foreach loop
sumList(ArrayList<Double> results) {
double total = 0.0;
for(double result : results) {
total += result;
}
return total;
}
And call sumList(results);
You can do:
ArrayList<Double> arr = new ArrayList<Double>();
To add elements to array in your case
double week_result = round(((inWatts/100)*use_hours*3600/1000)*0.54,2);
arr.add(week_result);
And to access this array from other classes, declare a getter method to return this ArrayList
public ArrayList<Double> getArray() {
return arr;
}
As your function calculation() returns a value of type double, you can simply store this value in an array, or any variable, of type double, for example:
public double[] values = new double[10];
values[0] = calculation();
This question already has answers here:
How to convert an ArrayList containing Integers to primitive int array?
(19 answers)
Closed 9 years ago.
This is my second program in Java, and its the first time I'm using an arrayList.
I searched about how to convert it, and used the methods i found, but I get an error...
package eliminarepetidos;
import java.util.ArrayList;
import java.util.Random;
public class Eliminarepetidos {
public static ArrayList<Integer> eliminaRepetidos (int[] vet){
ArrayList<Integer> retorna = new ArrayList<>();
for(int i = 0; i<vet.length; i++){
for (int j = i + 1; j < vet.length; j++)
if ((vet[i] == vet[j])&&(vet[i]!=0)) vet[j]=0;
if(vet[i]!=0) retorna.add(vet[i]); }
return retorna;
}
public static void imprime (int[] vet, int numElem){
System.out.print("Vetor resultante:");
for (int i = 0;i<numElem;i++)
System.out.print(" " +vet[i]);
}
public static void main(String[] args) {
int[] t;
t = new int[10];
Random generator = new Random();
for(int i = 0; i<10; i++)
t[i] = generator.nextInt(12) +9;
ArrayList<Integer> temporario = new ArrayList<>();
temporario = eliminaRepetidos(t);
int [] vetfinal = temporario.toArray(new int[temporario.size()]); //line with error
imprime(vetfinal,vetfinal.length);
}
}
How should I be using the command to make it work properly?
Thanks!
Any ArrayList can be converted to a simple array using toArray(<Type> t) (ArrayList<Thing> list -> Thing[] arr = list.toArray(new Thing[0])), but that's likely not your real question.
Your real question, based on the code you've shown, is far more likely: "how do I iterate over an arraylist?", to which the answer is: "the same as for arrays or any other collection, use the for loop in its foreach pattern":
int[] numbers = {...}
ArrayList<Thing> things = new ArrayList<Thing>();
thing.add(new Thing(...));
...
for(int i: numbers) {
System.out.println(i); // will print each element in the array
}
for(Thing t: things) {
System.out.println(t); // will print each element in the arraylist
}
This use of the for loop has been part of plain Java since v1.5 =)