I am getting 3 columns for each row from mysql table by using ResultSet. I am not sure about the number of rows I will get by using query. To store those rows I am using ArrayList as given code below:
while (rs.next())
{
String[] row = new String[numcols];
for (int i = 0; i < numcols; i++)
{
row[i] = rs.getString(i + 1);
}
rowsList.add(row);
}
rs.close();
When I debugged the code I found columns values are present in the ArrayList. Now I am unable to access the columns values because rowsList.get(index) will return only value at specific index but I have further 3 more values at that index how to access those values.
List.get() in your case will return a String array: String[]. You can access the elements of an array by using the [] index operators:
String[] row = rowList.get(0);
for (int i = 0; i < row.length; i++)
System.out.println(row[i]);
// Or you can use the enhanced for to loop through the array:
for (String s : row)
System.out.println(s);
If you want to process all rows:
for (String[] row : rowList) {
// Process row
for (String s : row) {
// Do something with the string
}
}
I would like to suggest you to learn about List.
And the second would be to create a class that holds everything that comes from your query.
And finally save each object of the class to the array.
Example
Suppose you get id, name and address columns from your query
Create a class
public class YourClass{
int id;
String name, address;
//create getters and setters or use a constructor
//example of setter to set field id
public void setId(int id){
this.id = id;
}
}
And then while retrieving the records from query, create an object of your class and set the columns as field of your class as follow:
YourClass anObject = new YourClass();
anObject.setId(id);// get similar columns from query
anObject.setName(name);
And finally add the object to the ArrayList as below:
yourArrayList.add(anObject);
To take care of multiple number of records you need to keep these code inside the while loop
And define your List before while loop as follow:
List<YourClass> yourArrayList = new ArrayList<YourClass>();
And I think this is the best approach as it uses OOP that you should begin using instead of using bare array.
you would want to specify what object is in the list. to achieve this make your List to List<String[]> rowsList = new ArrayList<String[]>();
then use your while loop
while (rs.next())
{
String[] row = new String[numcols];
for (int i = 0; i < numcols; i++)
{
row[i] = rs.getString(i + 1);
}
rowsList.add(row);
}
rs.close();
when you access each item in the list it will always return a String[] which you can iterate to get the values.
for(int i = 0 ; i< rowsList.size() ; i++){
rowsList.get(i);//will return a String[]
}
OR
for(String[] rows : rowsList){
//iterate the rows
}
Related
I want to use a data structure to store column names of a JTable with their respective indexes, so that I can select the corresponding data column. If I filter out a column name, then the name and the index gets removed, if I put it back, the index will be the same. If I want to swap two columns, the indexes change but the column names stay the same. It also has to be serializable. Can I do this with a HashMap<String,Integer>?
I managed to load it with values, I basically filtered the dataList with the selected columnNames. I'm not too familiar with maps. As far as a know, I can't "swap" key's in HashMap
private List<Object[]> data = new ArrayList<Object[]>();
private List<String> columnNames = new ArrayList<String>();
public CustomTableModel(List<Object[]> dataList, Map<Integer,String> columnNames) {
for (Map.Entry<Integer, String> set : columnNames.entrySet()) {
this.columnNames.add(set.getValue());
}
ArrayList<Integer> selectedColIndexes = new ArrayList<Integer>();
for (Map.Entry<Integer, String> set : columnNames.entrySet()) {
selectedColIndexes.add(set.getKey());
}
for(int n=0; n<dataList.size(); n++) {
Object[] selectedRow = new Object[columnNames.size()];
for(int j=0; j<selectedColIndexes.size(); j++) {
int index = selectedColIndexes.get(j);
selectedRow[j]=dataList.get(n)[index];
}
data.add(selectedRow);
}
}
I am trying to make some DataBase class. I know that I want each column to be represented as ArrayList.
I want to create Constructor as that
DataBase(String[] columnNames, String[] types)
so for example
DataBase({"Column1","Column2","Column3"},{"int","string","myOwnType"})
I tried to make it with HashMap which will have column name as key and ArrayList as value.
This is what I got so far.
public class DataFrame {
public HashMap<String, ArrayList> data;
public String[] names;
public String[] types;
public DataFrame(String[] names, String[] types) {
data = new HashMap<String, ArrayList>();
nazwy = new String[_names.length];
typy = new String[_types.length];
for(int i = 0; i < _names.length; i++) {
ArrayList column = new ArrayList<>();
data.put(_nazwy[i], column);
}
}
}
How can I create a column of type given in program? I thought about creating ArrayList and then make Map which will have label and that list, but I cant find how to do that.
In your method, this Loop is re initializing the arraylist so it is not possible to store the records.
for(int i = 0; i < _names.length; i++) {
ArrayList column = new ArrayList<>();
data.put(_nazwy[i], column);
}
Always good to have List. Map will represent each records with column names so that it will easy for processing.
ArrayList list = new ArrayList(50);
HashMap row = new HashMap(columns);
for(int i=1; i<=columns; ++i){
row.put(getColumnName(i),data(i));
}
list.add(row);
This is my function, to find a id from list by matching titles
public static int findIdByTitle(List<Integer> IDs, List<String> Titles ,String title){
for (int i = 0; i < IDs.size(); i++){
if (Titles.get(i).equals(title))
return IDs.get(i);
}
return 0;
}
This function search in model list and find id
But I can't use this because:
int id = findIdByTitle(Core.userSignIn.getBasicList().getGradeList().get(****?****).getID()
,Core.userSignIn.getBasicList().getGradeList().get(****?****).getName()
,spinnerGrade.getSelectedItem().toString());
I must give it a number position : ( see the lists.get(****?****).getID() or getName()
I want using that's function for all models not just for this model
give 2 lists and a matching word, use matching word to find position of that's in list, and give me a ID of this position
All of my model have ID , Title and some of them have ParentID
with help of Nitin , My problem has been resolved:
List<String> Titles = new ArrayList<>();
List<Integer> IDs = new ArrayList<>();
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
Titles = Core.userSignIn.getBasicList().getGradeList().stream().map(GradeList::getGradeName).collect(Collectors.toList());
IDs = Core.userSignIn.getBasicList().getGradeList().stream().map(GradeList::getGradeID).collect(Collectors.toList());
} else {
Titles = new ArrayList<>(Core.userSignIn.getBasicList().getGradeList().size());
IDs = new ArrayList<>(Core.userSignIn.getBasicList().getGradeList().size());
for (GradeList gradeList : Core.userSignIn.getBasicList().getGradeList()) {
Titles.add(gradeList.getGradeName());
IDs.add(gradeList.getGradeID());
}
}
educationList1.setiGradeID(findIdByTitle(IDs
,Titles
,spGrade.getSelectedItem().toString()));
You first have to convert your list to List of Integer and List of String and then pass it to your method. You can use below code if you are using Java 8:
final List<Integer> testList1 = BasicList().getGradeList().stream().map(Test::getId).collect(Collectors.toList());
final List<String> testList2 = BasicList().getGradeList().stream().map(Test::getName).collect(Collectors.toList());
Replace your class name in place of Test in above code.
Use below code for below java 8 env:
List<String> strings = new ArrayList<>(BasicList().getGradeList().size());
for (Test test : BasicList().getGradeList()) {
strings.add(test.getName());
}
Similar for Ids.
You need another loop if you want to get all Ids of your models, you can do something like this :
List<Integer> listId=new ArrayList<Integer>();
for(int i=0; i<BasicList().getGradeList().size(); i++) {
listId.add(findIdByTitle(BasicList().getGradeList().get(i).getID()
,BasicList().getGradeList().get(i).getName()
,spinnerGrade.getSelectedItem().toString()));
}
I'm trying to get the values for my function from the 2D List.
My 2D list value is defined as
List<List<String>> combined2d = new ArrayList<List<String>>();
After adding the values in to my List the structure is like below,
[[62744768, 62536400, 63689012, 63676486], [67888160, 67852422, 67299346, 68149470], [2017-09-06, 2017-09-05, 2017-09-17, 2017-09-15]]
I have a function with 3 parameters i.e,
FuncA(string param1,string param2,string param3)
{
//some operations
}
Now i want to pass the parameters of the FuncA by looping the 2D List Values.
For Loop 1
I have to get the 00,10,20 Index values from the List such as
62477,6780,2017-09-06
So that I will pass the parameters to my FuncA like
FuncA(62477,6780,2017-09-06)
For Loop 2
Like so for Loop 2 ,
FuncA(600,6785,2017-08-05)
For Loop 3
FuncA(12,646,2017-07-17)
Up-to N loops...
For a simple ArrayList I'm able to loop through like this
for(String value:Singlearraylist) {
FuncB(value);
}
As I'm new to java I couldn't able to find the solution for my problem here.
Appreciate your response
JAY
String[] strings = new String[combined2d.size()];
for (int i = 0; i < combined2d.get(0).size(); i++){
for (int j = 0; j < combined2d.size(); j++){
strings[j] = combined2d.get(j).get(i);
}
FuncA(strings[0] strings[1], strings[2]);
}
I think this will work fine for you.
If size of all the Lists are uneven, loop size should be minimum size of all given lists given in the 2-d list. Accordingly code can be written as forllows:
List<List<String>> combined2d = new ArrayList<List<String>>();
int minTemp = Math.min(combined2d.get(0).size(),combined2d.get(1).size());
int min = Math.min(minTemp,combined2d.get(2).size());
for(int i=0; i<min ; i+= 10){
FuncA(combined2d.get(0).get(i), combined2d.get(1).get(i), combined2d.get(2).get(i));
}
As #MadProgrammer suggested, create a class with data members param1 param2 param3with getters and setters and the list of this class's type, which you can use to iterate pass values to FuncA(...,...,...)
class Data{
String param1, param2, param3;
// constructors, getters and setters
}
List<Data> listData = new ArrayList<>();
for(Data temp : listData)FuncA(temp.getParam1(),temp.getParam2(),temp.getParam3());
And the way you create your list is the key here also as #MadProgrammer suggested in the comments.
This way, your code is a lot easier to read and debug.
I am working on a project that i have to compare all the tables between two huge databases and matching them. Actually this project aims to implement a kind of database fusion. For been more specific, if a row1 on table1.database1 describes the person "Michael" with id, phone, address, etc.. and the specific row2 on table2.database2 describes the person "Mike" with id, phone, address, etc... i have to decide after the comparison if "Michael" and "Mike" are the same persons or not.
I did the connection for both databases, I already catch up the tables, the columns and the row data. As i am not so familiar with java I don't know how to use the extracting data and start any comparison. Which is the best way to store and use them? arraylists? arrays? objects? vectors?
For example I have the following piece of code to catch the row data:
int j = 0;
while(resTablesData1.next()) {
ResultSetMetaData rsmd = resTablesData1.getMetaData();
int colCount = rsmd.getColumnCount();
System.out.println();
for (int k=0; k<colCount ; k++) {
String colName = rsmd.getColumnName(i);
Object o = resTablesData1.getObject(colName);
columnsArrayDB1[j][k] = o.toString();
System.out.println("|-----------------------------------------------------|");
System.out.print("| "+columnsArrayDB1[j][k]+" |"+"\t");
System.out.println("|-----------------------------------------------------|");
}
j++;
}
I have the same piece of code for both databases. I have to compare the columnsArrayDB1[0][0] with columnsArrayDB2[0][0] and so on... how to do that with an optimize way?
Is it better to use an Object which would represent the data of the row? for example:
public class RowDataObject {
public String col1;
public String col2;
// Etc
public RowDataObject(String aCol1, String aCol2 /*.....etc */ ) {
col1 = aCol1;
col2 = aCol2; //...etc
}
}
and then read data
List<RowDataObject> allRows = new ArrayList<RowDataObject>();
ResultSet rs = //Your Query
while (rs.next()) {
String c1 = rs.getString("A Column Name or Index");
String c2 = rs.getString("A Column second Name or Index");
//...etc
allRows.add(new RowDataObject(c1,c2......));
}
All of my work for this project processing dynamic values as I don't know beforehand the name of schemas/tables/columns etc. Please I am kindly requested some guidelines to start with because I am confused. My main problem is how to write the appropriate classes and create objects from them using the instances to my provided code.
Thanks in advance.
Since you're using o.toString() to get the String value of all returned rows, you could create an object to hold each column's value, e.g.:
class CellValue
{
int cellTye;
String cellValue;
CellValue(int cellType,String cellValue)
{
this.cellType=cellType;
this.cellValue=cellValue;
}
}
Create each new object using rsmd.getColumnType() and o.toString()
Add the objects to ArrayList for each row, and add each row to an ArrayList for each data source. you can then iterate through the two ArrayLists to compare the columns.
I haven't actually tested this, but something like:
ArrayList<ArrayList<CellValue>> cells = new ArrayList<>();
ResultSetMetaData rsmd = resTablesData1.getMetaData();
int colCount = rsmd.getColumnCount();
while(resTablesData1.next()) {
ArrayList<CellValue> row = new ArrayList<>();
for (int k=0; k<colCount ; k++) {
String colName = rsmd.getColumnName(i);
Object o = resTablesData1.getObject(colName);
row.add(new CellValue(rsmd.getColumnType(),o.toString());
}
cells.add(row);
}
When you compare the results of the two ArrayLists, you can compare cellType to make sure you're comparing cells of the same data type. If you want to get fancy, you can override .equals() in CellValue() to compare cellType and cellValue; you can then use cellValue1.equals(cellValue2) to see if it's a match.