binary search for query results - java

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.

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 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

Insert Elements to an ArrayList from ordered SQL

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.

Processing mysql records in java

I have a table with scores that contestants get after the complete a quiz. I then select the max(points) for each user and i group by user
select distinct userName, max(points) as numpoints
from tblscore
group by userName
order by numpoints desc
this gives me the order of all the highest scores for the user. i want to store these records in an array and process it, i want to rank each record plus i want to display records where the users have a tie. How can this be achieved? how will the array be set up and processed to cater for this.
Create a class (e.g. UserScore) with two fields - username and points
Get the ResultSet for the desired query (via a Statement)
Define a List<UserScore> list = new ArrayList<UserScore>
Loop the result set, using while (rs.next()) and on each iteration create a new instance of the UserScore class, set both of its fields (e.g. userScore.setPoints(rs.getInt("numpoints")), and then add the object to the list
If you can do with a List - go with it. If you really need an array - use list.toArray(..)
Alternatively, you can use apache commons-dbutils, and after you create the UserScore class, you just call:
List<UserScore> list = new BeanListHandler(UserScore.class).handle(resultSet);
Note that in this case your fields should be called the same way as your returned column names/aliases. You can also use the ArrayListHandler, which, instead of a list of the defined class, will give you a List<Object[]> where each column will be an element in the array.

Categories