Insert Elements to an ArrayList from ordered SQL - java

I am loading objects in an Java ArrayList from a SQL Query with an ORDER BY clause.
(1) Can I access that ArrayList with a foreach loop and get them back in
the order in which they were loaded?
(2) Similarly, can I consistently get the elements in the same SQL order by using get(n)? I.e. if the 3rd element in the SQL rowset was "x", will get(2) always retrieve that?

Can I access that ArrayList with a foreach loop and get them back in the order in which they were loaded?
Yes, List's are ordered collection .
Similarly, can I consistently get the elements in the same SQL order by using get(n)? I.e. if the 3rd element in the SQL rowset was "x", will get(2) always retrieve that?
Yes , As i said they are ordered , in the order they are inserted they can be retrieved in the same order.
List<String> ls=new ArrayList<String>();
ls.add("A");
ls.add("B");
ls.add("C");
for(String s:ls)
System.out.println(s);
System.out.println(ls.get(1));
Results:
A
B
C
B

sure you can, this is how List works. still you can use http://docs.oracle.com/javase/1.4.2/docs/api/java/util/LinkedHashSet.html

Yes ArrayList in Java is Ordered Collection. API says List is an ordered collection (also known as a sequence). The user of this interface has precise control over where in the list each element is inserted. The user can access elements by their integer index (position in the list), and search for elements in the list.
When you load from SQL to ArrayList you should exactly insert in the same order as of SQL.
code snippet should be like this
for (Each row starting from 0 in SQL) {
// add to arraylist using add method
list.add(sqlvalue);
}
for each iterator also maintain the same order.

Related

How to store listed values from a database to variables in Anylogic 8.7.1?

I am creating an agent based model in Anylogic 8.7. There is a point that I want to use query to get a List of values from a database table(rs_table) with a condition, here is the Java code that anylogic writes at the designated place:
(int) selectFrom(rs_table) .where(rs_table.tr.eq(1)) .list(rs_table.impact)
but I do not know how to store those values and how to reach them one by one. I would be grateful if you help me out thanks.
I would use a collection. Add a collection element from the "Agent" Pallet. The collection should have the following properties:
Collection Class: LinkedList
Element Class: Int
Use the following code:
collection.addAll(
selectFrom(rs_table) .where(rs_table.tr.eq(1)) .list(rs_table.impact)
);
Now, you can access the value from the collection as follows:
collection.get(i);
The "Iterate over returned rows and do something" option of the Insert Database Query wizard is precisely designed for this. It produces query code that loops through the returned list and prints each column's value to the console (via a traceln call); you just replace the code within the loop with what you actually want to do for each returned row (where the template code shows you how to get the value of each column in the row).
The wizard (if you use the QueryDSL form) will produce code like below:
List<Tuple> rows = selectFrom(rs_table)
.where(rs_table.tr.eq(1))
.list();
for (Tuple row : rows) {
traceln(
row.get( rs_table.tr ) + "\t" +
row.get( rs_table.impact )
);
}
(with extra row.get lines for any other table columns beyond the tr and impact ones).
(In Java terms, the query's list function returns a List of Tuple objects as the code shows.)

How to get first or last item from cqengine IndexedCollection with NavigableIndex

I have com.googlecode.cqengine.IndexedCollection object with NavigableIndex configured. I need to get first or last item from the index or iterator of the index in general.
I suppose this should be trivial. I know I can create Query object with queryOptions object, use it to retrieve iterator from IndexedCollection and get first object, but I'm not sure if it's optimal for performance. Surely it's not elegant.
With help of miradham I figured out that I need to remember indexes, since it's hard to pick up the right one if we have more of them. It will only work with NavigableIndex, we can't iterate base class Index
collection = new ConcurrentIndexedCollection<Data>();
index = NavigableIndex.onAttribute(Data.UNIQUE_TIMESTAMP);
collection.addIndex(index);
when I have the index:
try (CloseableIterator<KeyValue<String, Data>> iterator = indexUniqueTimestamp.getKeysAndValuesDescending(null).iterator()) {
if (iterator.hasNext())
return iterator.next().getValue();
}
return null;
One trick to retrieve the min or max (i.e first or last) object according on one of its attributes, is to use an all() query (which matches all objects in the collection), and to request that results should be returned in ascending or descending order of your attribute.
For example, if you had a collection of Car objects, you could use the following code to retrieve the car which has the highest (i.e. the max) price:
try (ResultSet<Car> results = cars.retrieve(
all(Car.class),
queryOptions(
orderBy(descending(Car.PRICE)),
applyThresholds(
threshold(INDEX_ORDERING_SELECTIVITY, 1.0)
)
))) {
results.stream()
.limit(1)
.forEach(System.out::println);
}
You can also change the limit to something other than 1, in case you want the top n most expensive cars to be returned.
The code above will work regardless of whether or not you actually have a NavigableIndex on the price. The bit about INDEX_ORDERING_SELECTIVITY is to actually request CQEngine to leverage the index (more details here).
or iterator of the index in general
You can use getIndexes() API of QueryEngine interface to retrieve set of Indexes.
Example code:
IndexedCollection<Car> indexedCollection = new ConcurrentIndexedCollection<Car>();
indexedCollection.addIndex(HashIndex.onAttribute(Car.CAR_ID), noQueryOptions());
List<Index<Car>> indexes = new ArrayList<Index<Car>>();
for (Index<Car> index : indexedCollection.getIndexes()) {
indexes.add(index);
}
NavigableIndex stores object in element in Map with attribute as key and set of object as value.
NavigableIndex does not maintain insertion order. First element of the index could be anything.
CQEngine is best designed for random access of object in collection not sequential.
Normal collections in java is best suited for sequence access with index.
one elegant way of accessing first element is to create SequentialIndex class and add it to concurrent collection. retrieve element using index as query.

How to rearrange rows of resultset data in java?

List userProcessedCountCol = new ArrayList();
while (iResultSet1.next()) {
afRealTimeIssuance afRealTimeIssuance = new afRealTimeIssuance();
Integer i = 0;
afRealTimeIssuance.setSub_channel(iResultSet1.getString(++i));
afRealTimeIssuance.setAgent_names(iResultSet1.getString(++i));
afRealTimeIssuance.setFtd(iResultSet1.getDouble(++i));
afRealTimeIssuance.setMtd(iResultSet1.getDouble(++i));
afRealTimeIssuance.setQtd(iResultSet1.getDouble(++i));
userProcessedCountCol.add(afRealTimeIssuance);
}
where afRealTimeIssuance is ActionForm
Using the above snippet I get something like below output
1 A 100
2 B 200
3 C 300
4 D 400
But I want to rearrange the output as
2 B 200
4 D 400
3 C 300
1 A 100
In short I want to rearrange the rows as I want.How to arrange the resultset data based on one particular value.Please guide
you can act as at two levels here:
Database level
Java level
At the database level the only way to manipulate the order of results to be returned is using ''ORDER BY ASC/DESC'' in your sql query. Note, that you can't rely on any other way to get the ordered results from the database.
At the java level you can store your objects like this:
- use a sortable collection. Make your action form comparable or implement a comparator that
allows to sort elements as you wish.
Then your can use This method to get the ordered collection by your own criteria.
You can consider also using TreeSet instead of ArrayList
This data structure will allow you to just add the data and given the comparator that you've defined in advance it will be always sorted. The addition has a logarithmic complexity though, so its up to you to decide.
Hope this helps
The ResultSet cannot be rearranged manually (only with sql) . What you can rearrange is your data structure that you hold your Objects
You can use an ArrayList of your row Objects and insert each row in the position you would like.
Lets say in your example, in the while loop:
userProcessedCountCol.add(index, element);
There are two ways of doing this. One you can modify the query to use ORDER BY clause to arrange the results. Second you can implement the Comparator interface and define your comparator classes and use Collection.sort(List list,Comparator c) to order the data.
Either use an ORDER BY clause in your SQL query, or Collections.sort() the List using a Comparator<afRealTimeInssuance>. The former is easier and places the load on the database, the latter more versatile as you can sort based on external information.
On a side note, you should name your classes using the Java conventions: AFRealTimeInssuance instead of afRealTimeInssuance.

Getting grouped data from database and process further in java

I have a table , say A ; now in A i have attribute ID as string and Time as DateTime.
Now the condition is that different entries to the table can have same ID and they have to be clubbed together and further do some refinement on it.
I am using java, I write the SQL query that
Select * from A group by ID;
Now i get this data in a huge list in java. Now what i do is
Set_ID=NULL;
for(each element in List)
{
if(Set_ID equals elements `ID` from table)
Add the element to the same list
else
Create new List and add element to the list. Change Set_ID to current `ID`
}
This way i get all the Entries with same Id in different lists and i can process further.
But is this the efficient way to this; comparing strings for each element.
Any change i can make, to make it better. Thanks.
Instead of reading all the data into a list & then processing it into sub lists, I'd process them directly into sub lists as you pull them from the database

binary search for query results

While inserting from spreadsheet to database I have rows which are already existed.so i need to check existed rows before inserting. I am doing it in Java.
In the spread sheet I have:
name
a
b
c
d
b
Database dbo.emp has:
name id
x 1
y 2
z 3
d 4
where the row is repeated. To find out the repeated row I need to search the arraylist. so i query both excel and sql database. I put result obtained by querying the Excel sheet into arraylist namexcel. And result obtained by querying dbo.emp into arraylist namedb.
Now I need to search which are the existed rows from binary search.
I wrote query and stored like this:
String ExcelQueryString2 = "select * from [Sheet1$]";
ResultSet SpreadsheetValues = stmt2.executeQuery(ExcelQueryString2);
List namexcel = new ArrayList();
while (SpreadsheetValues.next()) {
namexcel.add(SpreadsheetValues.getString("name"));}
String Querystring="SELECT Name from dbo.emp"
List namedb = new ArrayList();
ResultSet rs = statement.executeQuery(Querystring);
while(rs.next())
{
namedb .add(rs.getString("Name"));
}
My questions:
How do I implement binary search for these arraylist?
How do I omit this row before insertion?
How do I remove the duplicate row which is existed in exceldatabase?
Please provide me the code snippets.
binary search requires you to maintain the ArrayList sorted, and use Collections.binarySearch() for searching.
You might want to concider using a Set instead - which guarantees no duplicates as part of its behavior
You can consider using a LinkedHashSet, which ensures that no data is duplicated when data is added to it, whilst maintaining insertion order.
You can create set implementation using both lists currently you have. Then you can use set difference method approach used in this link.
http://www.java2s.com/Code/Java/Collections-Data-Structure/Setoperationsunionintersectiondifferencesymmetricdifferenceissubsetissuperset.htm
Actually you don't need go for a binary search. Before pass your list in to the binary search function you need to sort it. Which is a costly operation.

Categories