Access Values from an ArrayList That is inside another ArrayList - java

java.util.List records = new java.util.ArrayList();
java.sql.ResultSet rs = selectestatement.executeQuery(query1);
while (rs.next()) {
java.util.List record = new java.util.ArrayList();
record.add(rs.getString("WHLO").trim());
record.add("888509018579");
record.add(rs.getString("ITEM_CODE").trim());
record.add(rs.getString("ARRIVAL_DATE").trim());
record.add(rs.getString("PAIRS_PER_CASE").trim());
record.add(rs.getString("ATS").trim());
records.add(record);
}
In this code, Final arraylist is the "records array". This records arraylist contents few record arrays.
How can i access the 1st element of record arraylist from the records arraylist?

Don't use raw types:
List<List<String>> records = new ArrayList<>();
List<String> record = new ArrayList<>();
...
records.add(record);
This way records.get(i) will return a List<String> instead of an Object, so you can access the elements of the inner List:
String first = records.get(0).get(0);

What you really want is a class containing your row data.
class RecordData {
public String whlo;
public long someNumber = 888509018579;
public String itemCode;
public String arrivalDate;
public String pairsPerCase;
public String ats;
}
and then do
java.util.List<RecordData> records = new java.util.ArrayList<>();
while (rs.next()) {
RecordData record = new RecordData();
record.whlo = rs.getString("WHLO").trim();
record.itemCode = rs.getString("ITEM_CODE").trim();
record.arrivalDate = rs.getString("ARRIVAL_DATE").trim();
record.pairsPerCase = rs.getString("PAIRS_PER_CASE").trim();
record.ats = rs.getString("ATS").trim();
records.add(record);
}
In fact, you want to make the members private and accessible via getters and setters, and use LocalDate for the arrivalDate and int for the pairsPerCase member, but the first point is not using a List to store the retrieved values but wrap it in a business-oriented class.

You can do something like this
((ArrayList)records.get(0)).get(0) to access the first element of the array list that is in the first position of the records array list.
Please note that if you specify what does the records contains (in this case records will contains array lists) then you won't need to cast the element to array list.
List<List<String>> records = new ArrayList<ArrayList>();
{...}
records.get(0).get(0); //You don't need the cast because Java already knows that what it is inside records are Lists

Related

How do I import a populated ready-made ArrayList from another class in java?

I'm working with a large set of imported data and retrieving certain parts of it in the main method with 2 classes(WeatherStation, WeatherReading).The data is temperature readings at loads of weather stations(station id, name, lat, lon, year, time, temp etc) I made a third class (SoloSiteIds) whose sole purpose was to return a whole and complete ArrayList of the site ids with no duplication. But I cannot import the ArrayList from the other class into my main method. My SoloSiteIds class looks like this:
public class SoloSiteIds {
static ArrayList <Integer> siteIds = new ArrayList <Integer>();
public SoloSiteIds() {
}
public SoloSiteIds( ArrayList <Integer> siteIds) {
String[] weatherData = WeatherData.getData();{ // get the weather data
for (int i = 1; i < weatherData.length; i++) {
String line = weatherData[i];
String[] elements = line.split(","); // Split the data at ",
String siteid = elements[0]; // convert all the site id's at index 0 to integers
int id = Integer.parseInt(siteid);
if(!siteIds.contains(id)) {
siteIds.add(id);
}
this.siteIds=siteIds;
}
}
}
public static ArrayList<Integer> getSiteIds() {
return siteIds;
}
public ArrayList<Integer> setSiteIds(ArrayList<Integer> siteIds) {
return this.siteIds = siteIds;
}
}
The main method where I am trying to import the ArrayList "siteIds" looks like this:
WeatherStation thisStation = new WeatherStation (id, name, lat, lon);
WeatherReading thisReading = new WeatherReading(year, month, date, hour, windSpeed, temp);
SoloSiteIds siteList= new SoloSiteIds();
String[] weatherData = WeatherData.getData();{ // get the weather data
for (int i = 1; i < weatherData.length; i++) {
String line = weatherData[i];
String[] elements = line.split(","); // Split the data at ","
String siteid = elements[0]; // convert all the site id's at index 0 to integers
id = Integer.parseInt(siteid);
thisStation.setId(id);
thisStation.setName(elements[1]);
//parse the different elements into different data types
String stringLat = elements[2];
lat= Double.parseDouble(stringLat);
lat = thisStation.setLat(lat);
lat=thisStation.setLat(lat);
String stringLon = elements[3];
lon= Double.parseDouble(stringLon);
lat = thisStation.setLon(lon);
lat=thisStation.setLon(lon);
String stringTemp=elements[9];
temp=Double.parseDouble(stringTemp);
temp=thisReading.setTemp(temp);
Only the top part is relevant. I have tried lots of different variation of .set and .get using "thisList" instance and a new ArrayList like
ArrayList<Integer> siteIds = thisList.setSiteIds();
ArrayList<Integer> siteIds= SoloSiteIds.getSiteIds();
thisList=Siteids.setSiteIds();
thisList=SingleSoloSites.setSiteIds();
etc etc. This might look stupid but im just showing Ive tried numerous things and i am stuck
Thanks
I believe your problem is that you are initializing siteIds as an empty Arry list but you are not setting the data in a static way (the set Method is not static).
As far as I am aware of your situation, I belive that the SoloSiteIds class is unnescessary. I would solve your problem with an ArrayList declared in your main class and initialize with a getSoleIds() method also declared in your main class.
The getSoleIds() Method should contain the code currently in the SoleSiteIds initializer.

Deep copy an ArrayList containing objects with ArrayLists in Java

I have a problem to deep copy an ArrayList containing Attribute objects. After I have copied the ArrayList dataSet in a new one called trainingSet, I am trying to clear (of the trainingSet) all the content of the internal ArrayList of the Attribute called data. When I do so all the same content of the the ArrayList dataSet (data of dataSet) gets cleared, too. So in that case I have tried to deep copy all the content of the original list to the new one using the below tuts:
http://javarevisited.blogspot.gr/2014/03/how-to-clone-collection-in-java-deep-copy-vs-shallow.html#axzz4ybComIhC
https://beginnersbook.com/2013/12/how-to-clone-an-arraylist-to-another-arraylist/
How to make a deep copy of Java ArrayList
but I got the same behavior. So can someone please tell me how I can fix this problem and where the wrong thinking is?
Thank you for help.
ID3Algorithm.java
...
ArrayList<Attribute> dataSet = new ArrayList<dataSet>();
ArrayList<Attribute> trainingSet = new ArrayList<Attribute>(dataSet);
for(Attribute att : trainingSet) {
att.GetData().clear(); // At this point all the data in dataSet are cleared,too.
}
...
Attribute.java
public class Attribute
{
private String name;
private ArrayList<String> branchNames = new ArrayList<String>();
private ArrayList<String> data = new ArrayList<String>();
private ArrayList<Branch> branches = new ArrayList<Branch>();
private HashMap<String, Integer> classes = new HashMap<String, Integer>();
private ID3Algorithm id3;
private Leaf leaf = null;
public ArrayList<String> GetData() { return data; }
public Attribute(String attribName, ArrayList<String> attribBranchNames, ArrayList<String> attribData, ID3Algorithm algo) {
name = attribName;
branchNames = attribBranchNames;
data = attribData;
id3 = algo;
}
...
}
When you are assigning a value to trainingSet
ArrayList<Attribute> trainingSet = new ArrayList<Attribute>(dataSet);
You are only passing the references for the existing attributes into a new list. It is not a new list of different attribute objects. The first link you post, describes this process in detail. I would re-read it in depth.(The first example is a shallow copy)
http://javarevisited.blogspot.gr/2014/03/how-to-clone-collection-in-java-deep-copy-vs-shallow.html#axzz4ybComIhC
So when you call
att.GetData().clear();
You are clearing the orginal attribute objects data (which dataset also references)
Try creating new Attribute objects and assigning new data to each(copied from the orginal) then adding those to your trainingSet list.

Create a simple array with a List or a Set

First of all, I have created the object Sample, which looks like this:
public class Sample extends Model implements Comparable<Sample>{
public String content;
public Sample(String content) {
this.content = content;
}
}
Then, I create a List of Sample elements. After all that, what I'd like is to be able to create a simple String array in order to store this string content elements into a simple array to render it. My idea is to do something like:
String[] array = ...;
render(array);
With each component of this string being the content field of each Sample element. By doing that, I could "transfer" this array to operate with it later. How could I do that?
Using Java 8:
List<Sample> sampleList = ...;
String[] array = sampleList.stream()
.map(Sample::getContent)
.toArray(size -> new String[size]);
Using Java 7 or prior:
List<Sample> sampleList = ...;
String[] array = new String[sampleList.size()];
int i = 0;
for (Sample sample : sampleList) {
array[i++] = sample.getContent();
}
Use toArray() method forconverting Array to arraylist.
// create an empty array list with an initial capacity
ArrayList<Strng> arrlist = new ArrayList<String>();
// use add() method to add values in the list
arrlist.add("Anil");
arrlist.add("Vinod");
arrlist.add("Jaya");
arrlist.add("Arun");
// toArray copies content into other array
String list2[] = new String[arrlist.size()];
list2 = arrlist.toArray(list2);
Just a suggestion , if all you need is to create an array of contents , why not create a List from the Sample object and then invoke .toArray(). Did I miss something here ?

Hashmap holding a hashset - how to retrieve data

How do I obtain a list of all the objects that have the same value for a specific attribute out of HashMap<String,HashSet<String>> objects the String holds the attributes and the HashSet holds the list of values for the attributes!
Map<String,Set<String>> objects = new HashMap<String,Set<String>>();
// fill it up
String needle = "value";
List<String> results = new LinkedList<String>();
for(Map.Entry<String,Set<String>> entry : objects.entry set())
{
if(entry.getValue().contains(needle))
{
results.add(entry.getKey());
}
}
return results;

java: converting DynaBean (apache-commons-beanutils) to List

I use apache-commons-beanutils DynaBean class in order to fetch rows from a database and to handle them outside of the mysql function.
is there a way to convert a DynaBean to a List without iterating through each row and manually creating the list ?
thanks!
so far I didn't get any answers so I wrote the function that iterates through the rows and creates an ArrayList of HashMap type (String, Object).
public ArrayList<HashMap<String,Object>> convertDynaBeanListToArrayList(List<DynaBean> theList) {
ArrayList<HashMap<String,Object>> result = new ArrayList<HashMap<String,Object>>();
DynaProperty[] dynaProperties = null;
for (Integer i=0;i<theList.size();i++) {
DynaBean row = theList.get(i);
HashMap<String,Object> resultRow=new HashMap<String,Object>();
// each raw got the same column names, no need to fetch this for every line
if (dynaProperties == null) {
dynaProperties = row.getDynaClass().getDynaProperties();
}
for (Integer j=0;j<dynaProperties.length;j++) {
String columnName=dynaProperties[j].getName();
resultRow.put(columnName, row.get(columnName));
}
result.add(resultRow);
}
return result;
}

Categories

Resources