Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I want to insert a csv file content to a list .
col1,col2,col3
b,a,v
a,c,p
d,a,z
q,z,a
r,a,b
So that I can get a specific col value
for example : if 2 nd col then
a
c
a
z
a
I tried to insert it into a list
list: [b,a,v, a,c,p, d,a,z, q,z,a, r,a,b]
But how will I get the 2nd col value.
UPDATE
ArrayList<String> ar = new ArrayList<String>();
ar.add(line);
System.out.println("list: "+ar);
I am able to print first index.
using
System.out.println("get index: "+ar.get(0));
get index: b,a,v
but i need to get 'a' ie need all 2 nd column of the given data
As per your update, You need a from b,a,v . Here you can split the string and get the middle element i.e index 1 element. So following code snippet will get the 2nd value in each element and print it
for(int i=0;i<ar.size();i++) {
String[] tokens=(ar.get(i)).split(",");
System.out.println(tokens[1]);
}
With out using indexes of arraylist, You can use for each loop
for(String value:ar) {
String[] tokens=value.split(",");
System.out.println(tokens[1]);
}
A simple for loop will provide a trick,
Assign i with the initial value of columnnumber - 1, where columnnumber is the column value you are looking for,
for (int i = columnnumber - 1; i < args.length; i+=3)
{
System.out.print(args[i] + ", ");
}
Since each row contains 3 values and you have created a single list.
List is 0 index based. Index 1 will return the 2nd element from the list.
Use like this.
list.get(1)
You can do something like this.
ArrayList list = ... ;
...
int colId = 1;
int numCols = 3;
for(int i = colId; i < list.size(); i += numCols){
System.out.println(list.get(i));
}
Solution 1
Instead of list use List.so your list become
List<List>: [ [b,a,v], [a,c,p], [d,a,z], [q,z,a], [r,a,b]]
And to get any row you just have to call
List<List<String> list;
List<String> row = list.get(index); \\will return you corresponding row
String content = row.get(1); \\will return col2 value
Solution 2
if you go by single list then to get any element you must have to perform some calculation like
list<String> ar = new ArrayList<String>();
ar.get(row * 3 + column) // will return you column of row you want.
Note: row and column count starts from 0 not 1
You can use % operator if you are having only ArrayList.
Logic goes like this :
int colNo = 3 ; // column no which you want to get from list
for ( int i = 0; i < list.size(); i++ ) {
if ( i % colNo == 0) {
System.out.println(list.get(i));
}
}
However in your case it is recommended to use list of list.
Related
I am extracting data using some xyz logic. After extraction I am getting multiple list in each iteration.
for (int i= 0; i<= 5; i++)
{
for (int j= 0; j<= 5; j++)
{
//data extraction logic
lList1.add(value1);
lList2.add(value2);
lList3.add(value3);
}
//in each iteration I am getting list different
System.out.println(" lList1 for iteration "+i+"is: "+lList1);
System.out.println(" lList2 for iteration "+i+"is: "+lList2);
System.out.println(" lList3 for iteration "+i+"is: "+lList3);
}
I need to pass these list to database. Each list is associated with one column in db.
Example: lList1 is for column1, lList2 is for column2, lList3 is for column3 etc
What is best way to pass these list to db or to write these values row by row in java
output should be like
row 1 lList1 lList2 lList3 etc of first iteration list values
row 2 lList1 lList2 lList3 etc of second iteration list values etc
Can anyone help?
Create a class which will contain three members col1,col2 and col3 and make list of that class and use it.
class MyRow
{
public {col1datatype} col1;
public {col2DataType} col2;
public {col3DataType} col3;
}
your function
List<MyRow> lstRows = new ArrayList<MyRow>();
for (int i= 0; i<= 5; i++)
{
for (int j= 0; j<= 5; j++)
{
MyRow row = new MyRow();
row.col1 = value1;
row.col2 = value2;
row.col3 = value3;
llstRows.Add(row);
}
}
And use that lstRows accordingly at database transaction.
You can use Multidimensional Collections
ArrayList<ArrayList<Object>> a = new ArrayList<ArrayList<Object>>();
Result can be like that (based on your logic):
Multidimensional ArrayList: [[3, 4], [12, 13], [22, 23], [33,23]]
here is a full example :
ArrayList<ArrayList<Object>> list = new ArrayList<ArrayList<Object>>();
for (int i= 0; i<= 5; i++) {
//if you got all the values
list.add(new ArrayList<Object>(Arrays.asList(value1, value2, value3)));
//else you have to fetch them from another loop
for (int j= 0; j<= 5; j++) {
list.add(new ArrayList<Object>());
list.get(j).add(value1);
}
}
I would suggest the following flow:
First of all check the size of each listing and take the size of the biggest listing present, lets say its lList3 with 10 elements in it.
Make sure that your columns in DB are nullable meaning they can be NULL
Make a for loop to run 10 times (length of the biggest list) and insert lList1[i], lList2[i] and lList3[i] to the DB in each loop. Of course you will need to check first if the current index exists in the list, if not then insert NULL for that list column.
This way you will have each row in DB, the same way you need to list them out later in your front end. Also it will be easier to do any data search.
I would suggest in that case to serialize it to Json and store it in the column (since you use this approach with columns for lists).
When retrieving data from the DB, you can just deserialize it from Json to a List object.
For example Entity Framework is doing the same in .NET
if all list contains same length then make one common function for all ArrayList and iterate it with the loop of the maximum size ArrayList:
It should be like:
for(int i=0;i<lList1.size();i++) {
String insertQueryMainProduct = "INSERT INTO " + "" + tableName + "" + "(ColumnOneName,ColumnSecondName,ColumnThirdName)" + " VALUES('" +lList1.get(i)+ "', '" + lList2.get(i)+ "', '" + lList3.get(i)+ "')";
System.out.println("Query: " + insertQueryMainProduct);
statement.executeUpdate(insertQueryMainProduct);
Hope this will help you
I have a small problem, I want to go through a list and compare two objects of the array. Each object has 3 elements, I use a StringTokenizer to be able to remove the separator, so each object has 3 elements. I would like to know how to make a method that gets the third element of each object and compare them. And if that element is less than another delete that element and the 2 before it.
I tried to make them with an iterator but I wouldn't know very well that it started from the 3 element and increased the position by 3.
Iterator<Integer> it = lisM.iterator();
int num;
while (it.hasNext()){
num = it.next();
System.out.println(num);
}
Is --> if, I was wrong to put it in the picture
This only answers part of your question. I could not understand the question completely, please edit it and I can edit my answer.
You should not remove items from a list whilst in a for loop, therefore you can, for example, create another boolean list with the same size divided by 3 and just fill it with true Booleans then set the position divided by 3 to false if you want to delete the three items. Then you can create a new list, iterate over the boolean list and add 3 "Objects" which are actually Strings (thanks #JB Nizet) at a time, every time the boolean list element is true. When it is false you just don't add the elements and by doing so you are practically deleting the two elements before that element together with that element.
You casted a String to an int, that does not work you have to parse the Strings.
I corrected some of your code and added the boolean list here:
ArrayList<String> lisM = new ArrayList<>(); // here I initialise the list as an array list with strings.
ArrayList<Boolean> booleanList = new ArrayList<>();
for (int i = 0; i < lisM.size() / 3; i++) {
booleanList.add(true);
}
for(int i = 3; i < lisM.size();i+=3) {
int m = Integer.parseInt(lisM.get(i)); // here I changed the casting to parsing and moved it out of the for loop, there is no need to initialize it again every single time since you do not change it in the second for loop.
for (int j = 6; j < lisM.size(); j += 6) {
int m1 = Integer.parseInt(lisM.get(j));// here I changed the casting to parsing again.
if (m > m1) { // this makes no sense here because you are going over all of the elements of the list and comparing them to all of them. But I kept it here for the sake of example.
booleanList.set(i/3,false);
}
// if you want to go over the whole list you will have to clear the list and start over again for every element.
}
}
and here is how you could create the new list without the elements you do not want:
ArrayList<String> newLisM = new ArrayList<>();
for (int i = 0; i <booleanList.size(); i++) {
if(booleanList.get(i))
for (int j = 0; j < 3; j++) {
newLisM.add(lisM.get(i+j));
}
}
I have double dimensional array of dimensions 720x90. Let's denote rows by R and C as columns.
R1 = {C1,...,C90}
....
R720 = {C1,...C90}
Now, I want to see if any of the data in any of the rows appears anywhere else in any other rows. For instance, lets say the data in row 470 and column 67 is a duplicate of row 672 and column 34. In that case, I want to remove both row 470 and row 672 from the data set and continue checking. After I have checked all the rows, I want to print just the index of the rows that have survived. I have written a brute-force method of this. However, when I run this code, it never returns and I am not able to diagnose why. Also, is there a more efficient way to do this?
//check all the subsets of the interleaved data
public static int checkSubsets(String[][] subsets){
List subset = new ArrayList();
for(int i = 0; i< 720; i++){
for(int j = 0; j < 90; j++)
subset.add(subsets[i][j]);
}
Object duplicate;
Iterator itr = subset.iterator();
while(itr.hasNext()){
duplicate = itr.next();
while(itr.hasNext()){
subset.remove(duplicate);
itr=subset.iterator(); //to avoid concurrent modification
itr.next();
}
}
return subset.size();
}
Clarifications: Lets say I am iterating through looking at each value in the matrix. I take the first value in R1 C1 (row 1 - column 1). I find that these values are found somewhere in the 12, 346,123, 356 row. Then I remove all those rows from the matrix. So now the matrix is 5 rows smaller. I stop checking row 1 now and move onto row 2. I continue checking, skipping over row 12, 346, 123, and 356. Hence, I am after a row that is unique (has 90 values that are all unique).
I am not sure what the code you wrote has to do with the requirement, I will give you the approach of the answer yet you have to try it yourself first.
it is clear that you need to iterate on each row to check for possible duplicates yet this will cause a performance failure , you can overcome this with a smiple use of HashMap, first store each entry in the map , the key will be the value of the node of the array, and the value should be the coordinates of this node.
When iterating over the array for each row you should find the y coordinates from the map which is common between all nodes of the row, so duplicate rows detected.
In order to avoid keep checking the already removed rows try to store all the rows to be deleted and remove them once you are done, you can use Set to store them to avoid duplicate.
Good luck with the implemenation.
The algorithm is almost there, but helpfull data-structures are missing.
To add a bit of spice I used Java 8 somewhat.
As you did one can collect the values to check for duplicates.
However one needs to remember the first row of that value, as only there it is still unknown whether a duplicate exists.
public static int checkSubsets(String[][] subsets) {
// The results.
final Set<Integer> duplicateRows = new HashSet<>();
// From the first occurrence of a duplicate value we do not know it yet,
// so need to remember.
final Map<String, Integer> firstRowOfValue = new HashMap<>();
for (int i = 0; i < subsets.length; ++i) {
for (int j = 0; j < subsets[i].length; ++j) {
final String value = subsets[i][j];
Integer oldRow = firstRowOfValue.putIfAbsent(value, i);
if (oldRow != null) { // Duplicates
duplicateRows.add(i);
duplicateRows.add(oldRow);
// oldRow might already be added if third duplicate or same row.
}
}
}
IntStream.rangeOf(0, subsets.length)
.filter(i -> !duplicateRows.contains(i))
.forEach(System.out::println);
return subsets.length - duplicateRows.size();
}
The IntStream part would be in java 7:
for (int i = 0; i < subsets.length; ++i) {
if (!duplicateRows.contains(i)) {
System.out.println(i);
}
}
With java 7 you can safely substitute here putIfAbsent with put.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have a "for" loop that is creating a variable each time through the loop. I am attempting to insert the results into an empty array at the index of the "i" in the loop. From the best I can tell it seems I need to create a ArrayList vs. an Array to make this happen.
int varNum = 10;
Array someArr = new Array ();
for (int i = 0; i < 10; i++){
varNum = varNum +i;
someArr[i] = varNum;
}
On the first loop I want the 10 to be inserted in my array at the "0 index", 11 inserted at "1 index", 12 at the "2 Index".
**The important part is that the Array is not a set size, because I do not know how many indexes I will need in the array, so I want to add them as I needed.
If you use an ArrayList you can call add like this:
int varNum = 10;
ArrayList<Integer> someArr = new ArrayList<Integer>();
for (int i = 0; i < 10; i++)
{
varNum = varNum + i;
someArr.add(varNum);
}
This will allow you to dynamically fill the ArrayList dependent upon how many values it needs to hold.
Better use an ArrayList then, and use their .add() method
someArr.add(varNum)
I want to make a 2D ArrayList, with the number of columns already specified but not the rows.
For example, I want to create a table with 26 columns and 0 or 1 columns at first, then after each loop of doing something else, the number of rows will increase along with that loop.
When I increase the number of rows (length of an ArrayList of ArrayLists), I also want all 26 arrays to increase as well. What is the syntax for it?
And how would I index into, or add a new item into a specific location - say array[2][3] = item?
BTW this is a DFSA table converted from a NFSA table
You could have a list of lists, essentially something like so:
List<List<String>> table = new ArrayList<List<String>>();
Then add the 26 columns:
for(int i = 0; i < 26; i++)
{
table.add(new ArrayList<String>());
}
You can then have a method, called, say, addToColumn(int column, String value, List<List<String>> table) in which you do something like so:
for(int i = 0; i < table.size(); i++)
{
if(i == column)
{
table.get(i).add(value);
}
else
{
table.get(i).add("");
}
}
This should allow you to have lists which grow together. Of course, my assumption in the above is that you will be entering one element at a time.
Alternatively, you can do something like so:
public void addToColumns(Map<int, String> data, List<List<String>> table)
{
for(int key : data.keyset())
{
table.get(key).add(data.get(key));
}
for(int i = 0; i < table.size(); i++)
{
if(!data.containsKey(i))
{
table.get(i).add("");
}
}
}
The above algorithm should allow you to add items to multiple columns, while filling the rest up with empty strings. This should allow you to end up with rows of equal length. Also, the map will be used to store a key-value pair where the key is the column number, and the value will be whatever string you would like to throw in there. This will allow you to populate your table one row at a time.
You can simply create an array by giving only the number of rows:
int[][] array = new int[4][];
Now you may treat your array as the transpose of what you have defined so if you want to enter an element at 3rd column of 2nd row you can enter as transpose i.e.
array[3][2]=5;