save get values using arrayList java - java

In my example, I try to get val(0) and val(1) each time.
After for loop I need to save my values to use them for other calculations:
String[] columns = { "col1" , "col2" };
String[] y = { "TEST", "BUG" ,"ENH" };
List<int[]> values = new ArrayList<int[]>();
for (int j = 0; j < y.length; j++) {
// do some actions
for(int[] v : values) {
//v is the array for one iteration, use it like this:
int col1 = v[0];
int col2 = v[1];
values .add(v);
}
}
System.out.prinln(values) =>gives : []
Out of for loop, my values are raised, how do can I do to get my values after for?
Thanks

I don't understand the question either, but, here's my best guess at interpreting what the question is trying to do:
String[] columns = {"col1" , "col2"};
String[] y = { "TEST", "BUG" ,"ENH"};
int[][] values = new int[y.length][columns.length]; // 2D array
for (int j = 0; j < y.length; j++) {
for (k = 0; k < columns.length; k++) {
values[j][k] = table.getVal(j, columns[k]);
}
}

for (int value : values) {
// do something with value
}

Without knowing the structure of 'table', your data in the int array 'values' should be readily accessible via a for loop:
for (int v: value) {
//use 'v' here
}
or directly:
values[0];
values[1];
...etc
However, it might simply be a language barrier here preventing us from understanding the true problem.

If you want to get the values of all iterations after the loop, you first have to provide a fitting data structure. An easy way might be to use a 2-dimensional array:
int[][] values = new int[y.length][columns.length];
However, I'd recommend using a collection instead (assuming the original values has to be an array):
List<int[]> values = new ArrayList<int[]>();
Then fill that in your loop, either using array index y or just adding a new array in each iteration.
After the loop you can then iterate over the result, like this:
for(int[] v : values) {
//v is the array for one iteration, use it like this:
int col1 = v[0];
int col2 = v[1];
//or like this
for(int value : v) {
//value is the value of one column in one iteration
}
}
UPDATE:
In your updated code you're not putting anything into the list.
Note that you still have to create an array per iteration, get the values from your source (IIRC it was named table) and put them into the array, then add the array to the list using values.add(...).
Also note that the loop I added above is meant to read the values later, it doesn't show you how to fill the list in the first place.

Related

Remove items from custom arraylist implemetation without .remove

I'm working on a custom ArrayList implementation and I have one method where I'm trying to remove an item per conditions from an array such as E[] elements. The array is initialized by doing something like this:
String[] contents = {"chicken", "hippo", "goat"};
ArrayI<String> newarray = new ArrayI(contents);
newarray.chooser(new LongChooser());
It should remove words length 4 or less and return an array like this:
["chicken", "hippo"]
I'm trying not to use any built in methods, like remove(), clone(), arraycopy(), etc. I can't seem to get this to work, I've tried creating a duplicate array and trying to copy elements over like this:
E[] copy = (E[]) (new Object[this.size-1]);
for (int i = 0; i < size; i++) {
if (shorter) {
copy[i] = elements[i];
}
else {
for (int j = i; j<this.size-1; j++) {
elements[j] = elements[j+1];
}
elements[size-1] = null;
size -= 1;
}
for (int i =0; i< copy.length; i++) {
elements[i] = copy[i];
}
size -= 1;
I know this is not the correct way because they aren't the same size array and just returns [longword, longerword, null]. Also I'm pretty sure I should be using the size variable, but it doesn't seem to do much.
How do I get this to work? Thanks.
Create an array to hold the [filtered] results. Its initial size is zero.
Iterate through contents.
If the current element of contents needs to be retained, then
create a temporary array whose length is one greater than the array that holds the results.
copy the results array to the temporary array
set the last element of the temporary array to the current element of contents
assign the temporary array to the results array
Here is the code, using only simple arrays. I presume you can adapt it to your needs. Note that the last line is simply to check the value of newContents. It is not required.
String[] contents = {"chicken", "hippo", "goat"};
String[] newContents = new String[0];
for (String str : contents) {
if (str.length() > 4) {
String[] temp = new String[newContents.length + 1];
for (int i = 0; i < newContents.length; i++) {
temp[i] = newContents[i];
}
temp[newContents.length] = str;
newContents = temp;
}
}
System.out.println(Arrays.toString(newContents));

How to set size of two dimensional ArrayList?

So I'm trying to make an two dimensional ArrayList which has a set amount of ArrayLists, then each of those ArrayLists can contain as much as needed. I'm aware that arrays dynamically change size, but I'm trying to guarantee that is has at least a certain size in this case.
ArrayList<ArrayList<Integer>> integers = new ArrayList<ArrayList<Integer>>(10);
This doesn't work. I want to be able to set the location of a new Integer to one of the first dimension's indices, like so:
integers.get(7).add(new Integer(42));
This just gives me an IndexOutOfBoundsException, as though there are no Integer ArrayLists within the ArrayList. Is there a way to do this? I'm sure it's something simple I'm not seeing.
Array lists do not work like this. They are not arrays.
The list you created is backed by array of at least 10 elements, but itself it does not contain any, so you cannot refer to 7th or actually any one element.
integers.size() would return 0
integers.isEmpty() would return true
integers.get(0) would throw
Moreover, the list you initialized needs to be filled with lists themselves:
for (int i = 0; i < 10; ++i) {
row = new ArrayList<Integer>()
integers.add(row);
}
// now integers is a 10-element list of empty lists
Alternatively you could use primitive arrays (if you want to have a fixed-size rectangle).
int integers[][] = new int[10][];
for (int i = 0; i < integers.length; ++i) {
integers[i] = new int[10]; // rows are initialized to 0, as int is primitive
}
for (final int[] arr : integers) {
System.out.println(Arrays.toString(arr));
}
You can use a nested loop for this. Here is a short example:
import java.util.ArrayList;
public class PopulateArray {
public static void main(String[] args) {
ArrayList<ArrayList<Integer>> integers = new ArrayList<ArrayList<Integer>>();
int num_arrays_ to_populate = 10;
int num_indices_to_populate = 10;
for(int i = 0; i < num_arrays_to_populate; i++) {
integers.add(new ArrayList<Integer>());
for(int j = 0; j < num_indices_to_populate; j++) {
integers.get(i).add(0);
}
}
}
}
This would create an ArrayList of ArrayLists of ints and fill the top ArrayList with 10 ArrayLists and put a 0 in the first 10 cells of each. Obviously you can change any of those numbers to do what you want.
Note/Disclaimer: I wrote this on my phone, so if I missed a brace or semicolon, just comment and I’ll add it. The logic is there, though.

How to get column in 2-D array in java by Foreach loop?

I can get a row from a 2D array in java by foreach loop like :
int[][] array = new int[5][5]
for (int[] row : array) {
for (int c : row) {
}
}
But How can I get the column form 2D array by foreach loop ? Or is this possible to get column from 2D array by foreach loop ?
Thank you.
One alternative can be
int i =0;
for (int k : array[0]){
for (int[] row : array) {
System.out.println(row[i]);
}
i++;
}
It's not possible. You'll have to use the traditional for loop :
int[][] array = new int[5][5]
for (int j = 0; j < array[0].length; j++) {
for (int i = 0; i < array.length; i++) {
int current = array[i][j];
}
}
2D array is just a conceptual meaning. in fact 2d array is a combination of multiple one-dimensional array. Therefore you cannot access the columns without using a counter. even if you use for each loop you need a counter inside.
If you need to get all the columns then you can make a loop with number of column. But in this case all the rows should have the same number of columns (elements)
public static void main(String[] args)
{
int [][] yourArray = {{1,2,3,4,5,6},//sample 2d array with 6 rows and six columns
{1,2,3,4,5,6}, //this is actually a collection of 6 different 1d arrays
{1,2,3,4,5,6},
{1,2,3,4,5,6},
{1,2,3,4,5,6},
{1,2,3,4,5,6}};
int yourColumn = 3; //example of selected column (be careful columns start from 0)
for(int[] row: yourArray)
{
System.out.println(row[yourColumn]);
}
}

max value from arraylist part?

i have some int values stored in ArrayList1 (imagine a table with one column). I need to create another ArrayList2 (second column), which will have values, that are the max values of a range in ArrayList1, for example last 3 values. for example:
1 null
2 null
1 2
3 3
2 3
1 3
So the secondt column - ArrayList2, will contain for each row max value of the last 3 corresponding rows in ArrayList1. (same as in xls, B3=MAX(A1:A3)...).
I can do it by creating for each row with a loop that goes and finds out max value, or i can loop and create subArrayList and use collections.max, but both these solutions require a loop for every row, which isn't very practical, isnt there a simpler way? something like arrayList.max(1,3) to get the number straight away?
You can do something like the code I show below. You iterate the first array, calculating the maximum and updating the second array accordingly. Note that you need an extra array to store the intervals.
private void m1(List<Integer> array1, List<Integer> array2, int range) {
Integer[] rangeArray = new Integer[range];
//Iterate first array
for(int i = 0; i < array1.size(); i++) {
Integer x = array1.get(i);
rangeArray[i%range] = x;
//Update second array
if(i < range - 1) {
array2.add(null);
}
else {
int max = Collections.max(Arrays.asList(rangeArray));
array2.add(max);
}
}
}
Using Collections.max
int startFrom = 2; // configurable number
List<Integer> intList = Arrays.asList(1,2,1,3,2,1,4);
List<Integer> sortedList = new ArrayList<>();
for (int i = 0; i < intList.size(); i++) {
if(i < startFrom){
sortedList.add(null);
continue;
}
ArrayList<Integer> list = new ArrayList<Integer>(intList.subList(i -startFrom, i+1));
sortedList.add(Collections.max(list));
}
System.out.println(sortedList);
Output is :[null, null, 2, 3, 3, 3, 4]
Ok. So your size of list to compare can vary , in that case build an array list out of the numbers to compare say List<?> list = Arrays.asList( numbersToCompare );
then Collections.max( list ), the list should contain objects that can be compared in other words needs to be comparable. ( If not write your own comparator )

Appending to double Array method

So, I have a method like this
public String[][] getArgs(){
And, I want it to get results out of a for loop:
for(int i = 0; i < length; i++){
But how do I append them to the array instead of just returning them?
Create a String[][] array inside your method, fill this array inside a loop (or in any other way) and return that array in the end.
If you are sure you want to have only one for loop (instead of two, typical for 2-dimensional array), ensure your loop will go through the number of examples equal to the number of fields in your String[][] array. Then you can calculate the double-dimension array indexes from your single loop-iterator, for example:
for(int i = 0; i < length; i++){
int a = i % numberOfCollumnsInOutput;
int b = i / numberOfCollumnsInOutput;
String[a][b] = sourceForYourData[i];
}
(Of course which array dimension you treat as collumns (and which to be rows) depends on yourself only.) However, it is much more typical to go through an n-dimensional array using n nested loops, like this (example for 2d array, like the one you want to output):
for(int i = 0; i < dimensionOne; i++){
for(int j = 0; j < dimensionTwo; j++){
array[i][j] = someData;
}
}
For your interest. A sample code according to Byakuya.
public String[][] getArgs(){
int row = 3;
int column =4;
String [][] args = new String[row][column];
for(int i=0;i<row;i++)
for(int j=0;j<column;j++)
args[i][j] = "*";
return args;
}
You can make a LinkedList from that array, and then append the elements to it, and then create a new array from it. If you are not sure i'll post some code.

Categories