Adding double values to array list from strings - java

I'm trying to covert an array of strings into an array of doubles.
I'm fairly familiar with ArrayList<>() , but i see there is in an example code give, double[].
example: list = ["1" , "2" , "3"]
desired return: number = [1 , 2 , 3]
public double[] ConversionNumber
{
double[] sequence = new double[list.size()];
for(String element:list){
double val = Double.parseDouble(element);
sequence.add(val)}
return sequence;
when i do this, i get an error in Bluej compiler: "cannot find symbol- method add(double).
What is a good way to solve this (i'm a beginner at Java).
thanks!

If list is an array, then list.size() would fail. I think we can assume it should be a List<String>. And you access an array by index. Also, I assume it should be an argument to your method. Next, Java convention for methods names is camelCase.
public double[] conversionNumber(List<String> list) {
double[] sequence = new double[list.size()];
int pos = 0;
for (String element : list) {
double val = Double.parseDouble(element);
sequence[pos++] = val; // <-- post-increment
}
return sequence;
}

Generally, if you're working with Collections, you work with collections the whole way. It's bad form to use Lists for one thing, but arrays for another. So it's advisable to do this with a List<Double> instead of a double[]
public List<Double> parseDoubles(List<String> strings) {
List<Double> doubles = new ArrayList<>(strings.size());
for(String string : strings) {
doubles.add(new Double(string));
}
return doubles;
}

Below code will work for your case:
java.util.List<String> list = java.util.Arrays.asList("1", "2", "3");
public double[] ConversionNumber() {
double[] sequence = new double[list.size()];
int i = 0;
for(String element:list){
double val = Double.parseDouble(element);
sequence[++i] = val;
}
return sequence;
}

The error happens because arrays dont have an 'add' method. You will want to do something like:
double[] sequence = new double[list.length];
for(int i = 0; i < list.length; i++){
sequence[i] = Double.parseDouble(list[i]);
}
If list is an actual List not a String[] as I assumed, you would do:
double[] sequence = new double[list.size()];
for(int i = 0; i < list.size(); i++){
sequence[i] = Double.parseDouble(list.get(i));
}

Change your code here
for(String element:list){
double val = Double.parseDouble(element);
sequence.add(val)
}
to this if your list is a List:
for(int i=0;i<list.size();i++){
double val = Double.parseDouble(list.get(i));
sequence[i]=val;
}
if your list is an Array, then change to this:
for(int i=0;i<list.length;i++){
double val = Double.parseDouble(list[i]);
sequence[i]=val;
}

Related

incompatible types: int[] cannot be converted to java.util.List<java.lang.Integer>

I have a function that generates random arrays:
private static List<Integer> randomIntegerArray(int n) {
int[] array = new int[n];
for(int i = 0; i < array.length; i++) {
array[i] = (int)Math.random();
}
return array;
}
I'm getting the following error:
incompatible types: int[] cannot be converted to java.util.List
I'm not sure what the issue is here. This is an incredibly simple bit of code that I can't seem to get to work.
You're returning List<Integer>, but you're creating an int[]. They're completely different things! try this instead:
private static List<Integer> randomIntegerArray(int n) {
List<Integer> list = new ArrayList<>();
for(int i = 0; i < n; i++) {
list.add((int) Math.random()); // always returns 0
}
return list;
}
Or if you definitely want to use an array, change the method's declaration:
private static int[] randomIntegerArray(int n)
And be aware that Math.random() returns a value between 0 and 1, if you convert it to an int it'll always be 0.
You can have simpler code that actually produces random integers instead of zeros by directly using the Random class:
private static List<Integer> randomIntegerArray(int n) {
return ThreadLocalRandom.current().ints(n).boxed().collect(Collectors.toList());
}
This may return any Integer value; you can specify a range with additional arguments to the ints() method.
An alternative to Oscar's answer would be:
private static int[] randomIntegerArray(int n) {
int[] array = new int[n];
for(int i = 0; i < array.length; i++) {
array[i] = (int)Math.random();
}
return array;
}
As others have said, a List of type Integer is not the same thing as an array of type int.
Probably this wouldn't be the best choice but also works, altough you'll get always a zero list of integers as Peter Lawrey says:
private static List<Integer> randomIntegerArray(int n) {
Integer[] array = new Integer[n];
for(int i = 0; i < array.length; i++) {
array[i] = Double.valueOf(Math.random()).intValue();
}
return Arrays.asList(array);
}
Your error tells you that arrays and list are not compatible, a quick search would have shown you ways to convert one to the other like Arrays.asList ().
Secondly Math.random returns a random number between 0.0 and 0.9 so you need to multiply by the number you want.
You may need to go through a quick tutorial on Java first.
All the best.

How to sort multidimensional string array by one column in integer value in java?

I have for example this multidimensional array:
String[][] array = new String[10][2];
In the first column I have strings which are in my case usernames, but in the second column I have strings which should represent integers. Now I want to sort the array like this:
Before:
Petter 543
John 276
Jay 1879
Alf 5021
etc.
After:
Alf 5021
Jay 1879
Petter 543
John 276
etc.
So I want the highest value at the top and the lowest at the bottom but don't mess up the names. All I found till now is how to sort bother all integer multidimensional arrays or only string multidimensional arrays and not how to just sort the second column based on just integers.
I once got it sorted but it was sorted in "alphabetic" way:
So 1000 was the highest score
12 was the second highest score and
999999 was the lowest score.
Like 1 represents "a" and 9 represents "z".
Using Java 8 streams:
String[][] out = Arrays.stream(names)
.sorted(Comparator.comparing(x -> -Integer.parseInt(x[1])))
.toArray(String[][]::new);
If the person and the id are associated in some way, then it would be better to create a class that models them (POJO), make that POJO class comparable, define a list of the POJO and use Collections#sort to sorted according to the desired criteria...
another thing to consider is that you have a 2 dimentional String array
String[][] but your question states
...How to sort multidimensional string array by one column in integer value in java?
which means that you need to consider to parse the string to integer... (just as a nice hint)
public class MyPojo implement Comparator<MyPojo>{
private String name;
private String id;
...implements the method of the comparator
}
the do in the main test class
List<MyPojo> mList = new ArrayList<MyPojo>();
mList.add(...);
mList.add(...);
mList.add(...);
Collections.sort(mList);
System.out.println(mList)
Loop over the array until its sorted and swap each time it's not.
public static void main(String[] args) {
String[][] array = new String[4][2];
array[0][0] = "Petter"; array[0][1] = "543";
array[1][0] = "John"; array[1][1] = "276";
array[2][0] = "Jay"; array[2][1] = "1879";
array[3][0] = "Alf"; array[3][1] = "5021";
System.out.println(Arrays.deepToString(array)); // [[Petter, 543], [John, 276], [Jay, 1879], [Alf, 5021]]
sortArrayByScore(array);
System.out.println(Arrays.deepToString(array)); // [[Alf, 5021], [Jay, 1879], [Petter, 543], [John, 276]]
}
public static void sortArrayByScore(String[][] array) {
String tmpName, tmpScore;
boolean sorted = false;
while (!sorted) {
sorted = true;
for (int i = 0 ; i < array.length - 1 ; i++) {
if (Integer.parseInt(array[i][1]) < Integer.parseInt(array[i+1][1])){
sorted = false;
// SWAP NAMES
tmpName = array[i][0];
array[i][0] = array[i+1][0];
array[i+1][0] = tmpName;
// SWAP SCORES
tmpScore = array[i][1];
array[i][1] = array[i+1][1];
array[i+1][1] = tmpScore;
}
}
}
}
My advice would be to take the second column of the 2D array, and put it in its own integer array. Then, call Arrays.sort() on that array. Finally, place the newly sorted array back into the 2D array as string values. Here is what it should look like,
int arr = new int[10];
String[][] copy = new String[10][2];
for(int i = 0; i < array.length; i++){
arr[i] = Integer.parseInt(array[i][1]);
System.arraycopy(array[i], 0, copy[i], 0, array[i].length);
}
Arrays.sort(arr);
for(int i = 0; i < array.length; i++){
array[i][1] = String.valueOf(arr[i]);
}
//fixing the names
for(int i = 0; i < copy.length; i++){
for(int j = 0; j < array.length; j++){
if(copy[i][1] == array[j][1]){
array[j][0] = copy[i][0];
break;
}
}
}
EDIT: To address the order of the names, I changed the code to include a copy of the 2D array so that after rewriting the integer values in order, a check is done to see where each integer moved. For each integer, the corresponding name is transferred to where the integer moved.
Use a comparator to sort the items in an array. In your case you have an array of arrays so you need a comparator for an array. You can use a Comparator of String array which assumes the 2nd item is the value.
public class SomeComparator implements Comparator<String[]> {
/**
* Assumes each row is length 2 and the 2nd String is really a number.
*/
#Override
public int compare(String[] row1, String[] row2) {
int value1 = Integer.parseInt(row1[1]);
int value2 = Integer.parseInt(row2[1]);
// compare value2 first to sort descending (high to low)
return Integer.compare(value2, value1);
}
}
Then you can sort using Arrays.sort like this
String[][] data = newData(); // or however you get your data
Arrays.sort(data, new SomeComparator());
You can use a Comparator that sorts the inner String[] items on the Integer value of the second element, instead of using the default string sort:
Arrays.sort(array, (o1, o2) -> Integer.valueOf(o2[1]).compareTo(Integer.valueOf(o1[1])));
Here you are using lambda syntax to do the same as would be achieved by:
Arrays.sort(data, new Comparator<String[]>() {
#Override
public int compare(String[] o1, String[] o2) {
return Integer.valueOf(o2[1]).compareTo(Integer.valueOf(o1[1]));
}
});

Jagged Array sorting in java

Recently I faced a question in an interview and I was unable to make logic for this question. I have an array like
[ 1,'a',45,'h',56,'d',2,'t',6,'p' ] . How to sort this array ? Output should be in this manner..
intArray = [1,2,6,45,56]
charArray= ['a','d','h','p','t']
If anybody knows its logic please comment. It would be a great help.
Thanks !
One way would be separate the integers and then sort-
Object[] objects = new Object[]{ 1,'a',45,'h',56,'d',2,'t',6,'p' };
List integers = new ArrayList<Integer>();
List characters = new ArrayList<Character>();
// Check and store integers and characters
// Doesn't validate and assumes you either have integers or characters
for(Object o : objects){
if(o instanceof Integer){
integers.add(o);
} else {
characters.add(o);
}
}
//Sort them separately
Collections.sort(integers);
Collections.sort(characters);
System.out.println(integers);
System.out.println(characters);
First of all separate the integers and character into different
arrays by checking its instance type.
If characters are stored in ASCII form (in java it is stored in ASCII form) you can directly sort them using any of the sorting algorithm, treating each value as integer only.
Similarly you can apply any sorting algorithm on integer array.
The following code produces desired result:
import static java.util.stream.Collectors.*;
final Map<Class<?>, Set<Object>> result = Stream.of(array) //
.collect(//
groupingBy(x -> x.getClass(), //
mapping(x -> x, toCollection(TreeSet::new))));
to view results:
System.out.println(Arrays.toString(result.get(Integer.class).toArray()));
System.out.println(Arrays.toString(result.get(Character.class).toArray()));
Below is the implementation of it. I have used two for loops so that we can easily find out the length of the two new subarrays instead of initializing it with the base array;s length.
I have tried not to use any in-built methods except Arrays.sort(). You can also write your own code to sort these two sub arrays.
public static void main(String[] args) {
Object[] array = { 1, 'a', 2, 'f', 5, 'b', 3 };
int intLoc = 0;
int charLoc = 0;
for (int i = 0; i < array.length; i++) {
if (array[i] instanceof Integer) {
intLoc++;
} else {
charLoc++;
}
}
int intArray[] = new int[intLoc];
char charArray[] = new char[charLoc];
for (int i = 0; i < array.length; i++) {
if (array[i] instanceof Integer) {
--intLoc;
intArray[intLoc] = (int) array[i];
} else {
--charLoc;
charArray[charLoc] = (char) array[i];
}
}
Arrays.sort(intArray);
Arrays.sort(charArray);
System.out.println(Arrays.toString(intArray));
System.out.println(Arrays.toString(charArray));
}

Converting <string> into float[]

Got this code (not working):
for (int i = 0; i < splitSource.length; i++) {
float[] nr = Float.parseFloat(splitSource[i]);
}
I have an collection of strings...
List<String> stringCollection = new ArrayList<>();
Previously, every string from the list is treated separately extracting from it the necessary and unnecessary characters and the final result is a string of pure numbers.
Now, I need to convert those numbers from String into Float, but i get the error of "float cannot be converted to float[]"...
float[] nr= new float[splitSource.length];
for (int i = 0; i < splitSource.length; i++) {
nr[i] = Float.parseFloat(splitSource[i]);
}
Float.parseFloat returns single float number, not array. Also, declaring float[] nr inside for cycle makes no sense. Result will be lost when cycle ends.
The method Float.parseFloat(String) delivers a float. Not an array of float. So just write
float[] nr = new float[splitSource.length];
for(...) {
nr[i] = Float.parseFloat(splitSource[i]);
}

Java-Hibernate from List of values to multidimensional double arrays

With the following snippet I am trying to build from a List returned from Hibernate a multidimensional array , double[][]:
The data list gets to makeSet, the makeSet tries to return a [][] double array. The optimal, is that I don't know how many arrays should I have. So I tried calling makeInnerSet but unless I create a new double[][] ix, iy in the code, the code does not iterate well.
Is there a way to know the columns of an array [][] ?
Perhaps is there another approach to the problem ?
It's mandatory to take back the scalar values of Hibernate and make them double[][] of what ever size. Any help ?
List data = qry.list();
double[][] inputData = makeSet(data);
public double[] makeInnerSet(List data, double[] ix, int col ){
int i = 0;
Iterator<?> itr1 = data.listIterator();
while (itr1.hasNext()) {
Object[] result = (Object[]) itr1.next();
if (result[col] != null) {
double res1 = (Double) result[col];
ix[i] = res1;
}else{
ix[i] = 0;
}
i++;
}
return ix;
}
public double[][] makeSet(List data){
Iterator<?> itr1 = data.listIterator();
double[] ix = new double[data.size()];
double[] iy = new double[data.size()];
double[][] x = { makeInnerSet(data, iy,0), makeInnerSet(data, ix,1) };
return x;
}
EDIT
Well making making the code :
double[][] x = {
makeInnerSet(data, new double[data.size()],0),
makeInnerSet(data, new double[data.size()],1)
};
Half-found my answer...seconds later...
I certainly now don't need the ix, iy. But how do I take the number of columns in the List ?
Assuming all arrays in the list have the same size (because otherwise makeinnerset would bomb ,too):
int columns = ((Object[])data.first()).size()
the code gets the first array and get its size which should be the same for all arrays.

Categories