Java and Kotlin interoperability, managing data using Koltin Lambda? - java

So essentially, I am using java to obtain information, and then I am using Kotlin to manage the information. So what I have done so far is, I have stored my information into a ArrayList called tableData in java, I store all my elements into this list (I should have used a better name here) and then returned the list. My java code:
public static ArrayList<String> readAllData () {
//Connecting to database
Connection con = DbConnection.connect();
//Preparing statement
PreparedStatement ps = null;
//result set declaration
ResultSet rs = null;
//tableData String array
ArrayList<String> tableData = new ArrayList<String>();
try {
//Database initialization
String sql = "SELECT * FROM ProjectInfo";
ps = con.prepareStatement(sql);
rs = ps.executeQuery();
while (rs.next()) {
//for each iteration store the data into variable a from column projectName
String a = rs.getString("projectName");
//print out each element
//System.out.println("a = " + a);
tableData.add(a);
}
//other catch exceptions
} catch (SQLException e) {
System.out.println(e.toString());
} finally {
try {
rs.close();
ps.close();
con.close();
} catch (SQLException e){
System.out.println(e.toString());
}
}
//System.out.println(tableData);
//return all the data that has been stored into this array
return tableData;
}
In Kotlin, I created a property class called GettingData and passed one parameter projectName: ArrayList<String>. Then i moved onto actually printing out the data
class GettingData(var projectName: ArrayList<String>) {
}
fun ManageData() {
var arrayData = listOf<GettingData>(GettingData(DbConnection.readAllData()))
var projectNameData = arrayData.map {it.projectName}
for (projectName in projectNameData) {
println(projectName)
}
}
All my elements are printed out, however I cannot use the filter functions to call specific elements from the arrayList? I want to be able to call every element and print them out in a alphabetical order? I tried filter, sortedWith and find functions but I cannot seem to get it working. How can I achieve this?

I think your question boils down to wanting to print a list of strings in alphabetical order.
You can use the sorted() function:
for (projectName in projectNameData.sorted()) {
println(projectName)
}

Related

CYPHER QUERY :-Change Arrayreturned by collect(n.name) in cypher query to Arraylist (util)

Neo4j cypher query collect() return Array in result. In order to iterate it we need it to add in arrayList. The previous process we used is not helping us and throwing an exception.
PREVIOUS CODE:-
public String GettingCurrentDate() {
Connection connect = null;
String query=null;
try {
connect = graphdbConnect();
Statement stmt = connect.createStatement();
query="match(n:learner) "
+ " return collect(n.name) as ids";
System.out.println(query);
ResultSet rs = stmt.executeQuery(query.toLowerCase());
while(rs.next()){
Array idsList=rs.getArray("ids");
System.out.println("idsList :: "+idsList);
ArrayList<String> userIds = new ArrayList<>();
String[] userIdsArray = (String[])rs.getArray("ids").getArray();
for(String id : userIdsArray) {
userIds.add(id);
System.out.println(userIds+"------userId");
}
}
}
catch(Exception e) {
e.printStackTrace();
} finally {
if(connect!=null) {
try {
connect.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return "sucess";
}
This code is getting exception java.sql.SQLFeatureNotSupportedException: get array
Question:- HOW WILL WE GET THE DATA FROM COLLECT() function and iterate it
Have you checked to see the actual object returned by
resultSet.getObject("ids")
If it's like user defined procedures, collections in Cypher get returned as ArrayLists, so try casting the returned object to an ArrayList and see if that works for you.
Cast Object to ArrayList
Object idsList=rs.getObject("ids");
System.out.println("idsList :: "+idsList);
ArrayList<String> userIds = (ArrayList<String>) idsList;
System.out.println("List2 Value: "+userIds);

Passing ArrayList to separate class?

I have a code that reads from an SQL Database and saves each column of information into an ArrayList. I need to pass each ArrayList into a separate class where I can store the lists as single pieces of information (IE: Information in the first part of ArrayList1 goes with information in the first part of ArrayList2 etc...) and then sort them. I don't know how to pass that information to another class though. This is a section of my main method that stores the information into a list. I need this information passed to a separate class called List.java:
String SelectStatement1 = "SELECT InvoiceID FROM Invoice;";
ps = conn.prepareStatement(SelectStatement1);
rs = ps.executeQuery();
int count = 0;
while (rs.next()){
count++;
}
ps.close();
ps = conn.prepareStatement(SelectStatement1);
rs = ps.executeQuery();
ArrayList<String> InvoiceIDList = new ArrayList<String>();
String InvoiceID = null;
int p = 0;
while (p < count){
rs.next();
InvoiceID = rs.getString("InvoiceID");
InvoiceIDList.add(InvoiceID);
p++;
}
ps.close();
p = 0;
Edit: This is only a section of my code, I already have the code open and close the connections, I only need information on how to pass the ArrayList to another class for sorting.
Create a method in your other class like this:
public void receiveList (ArrayList<String> invoiceIDList) {
// Do something with invoiceIDList data
}
It may not be a bad idea to create a constructor in your "List" class, that accepts the ArrayList and creates the class instance with the required data
Also, please change the name of that class!! It will be confusing to others who read your code, as you are passing an ArrayList already!
EDIT:
You could also have your class implement the List interface, which would make things a lot easier for you, because you can insert data into your class based on the position of the data in the ArrayList.
public class yourClass implements List<String> {
// Your class methods and variables...
}
If you wanted to expand on this to allow more than just Strings, you can change to: List<T>, this would give you a more generic approach.
First, I suggest you perform a SELECT COUNT() instead of iterating your rows in your first query. Then remember to close() both the PreparedStatement and ResultSet. Finally, I would suggest you program to the List<String> interface. Putting it all together like,
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
Connect to your database and initialize conn.
int count = 0;
try {
String query1 = "SELECT COUNT(InvoiceID) FROM Invoice;";
ps = conn.prepareStatement(query1);
rs = ps.executeQuery();
if (rs.next()) {
count = rs.getInt(1);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
rs.close();
} catch (Exception ignored) {
}
try {
ps.close();
} catch (Exception ignored) {
}
}
The above block of code is necessary to close() both rs and ps in the correct order with the finally Block.
List<String> invoiceIdList = new ArrayList<>();
try {
String query2 = "SELECT InvoiceID FROM Invoice;";
ps = conn.prepareStatement(query2);
rs = ps.executeQuery();
while (rs.next()) {
invoiceIdList.add(rs.getString("InvoiceID"));
}
} catch (SQLException e) {
e.printStackTrace();
} finally { // <-- it's identical to the finally block above.
try {
rs.close();
} catch (Exception ignored) {
}
try {
ps.close();
} catch (Exception ignored) {
}
}
// now you can pass invoiceIdList elsewhere...
if (!invoiceIdList.isEmpty()) {
doSomething(invoiceIdList);
}

Prepared Statement only retrieves the first row

I'm developing a web application in which users can insert a number of "products". These products will be inserted in a MySQL database. I have a problem when I try to retrieve data from a table of my database. Here is my method:
public ArrayList<Product> getProductByAppId(int appId) {
ArrayList<Product> list = new ArrayList<Product>();
String query = "select prodId from app_prod where appId = ?";
try {
preparedStatement = connection.prepareStatement(query);
preparedStatement.setInt(1, appId);
resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
Product item = getProductById(resultSet.getInt("prodId"));
list.add(item);
}
return list;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
This method simply gets an int as a parameter and retrieves from the table app_prod all the objects I have stored. The method getProductById it's an helper method and it works properly. When I try to debug my code, I see that I enter in the while cycle only once! So all I see is the very first element in my DB, but I have more than a single product in my DB.
To make things shorter, I've omitted methods to open and close connection because they work properly.
I think the error is something very obvious, but I can't really see it.
OK the problem is the following:
resultSet is declared as a global variable and is being used by both methods.
When the second method changes its contents and gets through it by :
resultSet.next();
And reaches the end of it:
The main outer loop tries to do resultSet.next(), it directly exits from the loop since it had already reached its end beforehand in the getProductById method.
List<Product> list = new ArrayList<>();
try (PreparedStatement preparedStatement = connection.prepareStatement(query)) {
preparedStatement.setInt(1, appId);
try (resultSet = preparedStatement.executeQuery()) {
while (resultSet.next()) {
Product item = getProductById(resultSet.getInt("prodId"));
list.add(item);
}
return list;
}
} catch (Exception e) {
e.printStackTrace();
}
The try-with-resources ensure that statement and resultset are closed (even despite the return).
Also now the variables are local. And that might be the problem: maybe you reused those global fields in getProductById. resultSet would be my guess. (Pardon me.)

Prepare statement inside a loop

I trying execute a query inside a loop.I am tryning this code :
public List<Products> DisplayProducts(String []a)
{
ResultSet rs = null;
List<Products> Data=null;
try
{
for(int i=0;i<a.length;i++)
{
String query = "select * from products where Brand=?";
PreparedStatement stmt=DataBaseConnection.DBConn.getConnection().prepareStatement(query);
stmt.setString(1, a[i]);
rs=stmt.executeQuery();
}
if(rs.next())
{
rs.beforeFirst();
Data=new ArrayList<Products>();
while(rs.next())
{
Products p=new Products();
p.setTitle(rs.getString(2));
p.setCategory(rs.getString(3));
p.setSubCategory(rs.getString(4));
p.setSubCategoryTwo(rs.getString(5));
p.setPrice(rs.getInt(6));
p.setFlavour(rs.getString(7));
p.setImage(rs.getString(8));
p.setBrand(rs.getString(9));
p.setInstock(rs.getString(10));
p.setInstockQty(rs.getInt(11));
Data.add(p);
}
}
return Data;
}
catch(Exception e)
{
System.out.println(e.getStackTrace());
return null;
}
}
I have a jsp page where I have Checkboxes and I am displaying multiple products on this page. I am sorting this products by BRANDS. User selects Brand by checking checkbox.
I am passing the value of checkbox to a servlet and on that servlet calling function Display Products:
String arr[]=request.getParameterValues("On");
List<Products> Data=new SessionBeanClass().DisplayProducts(arr);
Please tell me how do I execute this and get the result ?
I suppose you need to return the list of all products with the checkbox ticked. In that case i suppose you have a logic error here. This method only returns the last Product record.
Instead of looping through different id you could use 'IN' clause and return all at once. There are many differet ways to achieve IN clause. The one given below is a simple alternative. You could check for various operations in http://www.journaldev.com/2521/jdbc-preparedstatement-in-clause-alternative-approaches or http://www.javaranch.com/journal/200510/Journal200510.jsp#a2
In addition to that try following java naming conventions and clean up connections using finally
Try
public List<Products> DisplayProducts(String[] a) {
ResultSet rs;
List<Products> data;
PreparedStatement stmt;
try {
StringBuilder param = new StringBuilder();
for(String str : a){
param.append("'").append(str).append("', ");
}
String query = "select * from products where Brand in (" + param.substring(0, param.length() - 2) + ")";
stmt = DataBaseConnection.DBConn.getConnection().prepareStatement(query);
rs = stmt.executeQuery();
if (rs != null) {
data = new ArrayList<Products>();
while (rs.next()) {
Products p = new Products();
p.setTitle(rs.getString(2));
p.setCategory(rs.getString(3));
p.setSubCategory(rs.getString(4));
p.setSubCategoryTwo(rs.getString(5));
p.setPrice(rs.getInt(6));
p.setFlavour(rs.getString(7));
p.setImage(rs.getString(8));
p.setBrand(rs.getString(9));
p.setInstock(rs.getString(10));
p.setInstockQty(rs.getInt(11));
data.add(p);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
stmt.close();
}
return data;
}
Explanation as per comment
Ok. I suppose your idea here is to pass a set of brand names say adidas, nike, etc.. and select all the product details. So you need to do something like select * from products where Brand in ('adidas', 'nike'). This will give you all the products. So for this you pass the selected brand names as a string array. So what i did was to get the values from array and format it and make it as argument for IN clause. So of IN clause it needs comma separated values. Since its a Sting we need to give single quote ' as well. So from an array [adidas, nike] i need to construct 'adidas', 'nike'. That is what done in the for loop, appending ' and , (comma). So after for loop we'll have an additional comma and space at the end (e.g. 'adidas', 'nike', ). In order to remove this i remove the last two charaters by taking substring as param.substring(0, param.length() - 2). This is fed to the query and retrieve the result.

ArrayList keep returning 0

I retrieve the data from database and loop it thru an array to display the like amount.
public void SetUpLikeAmount() {
int likes = 0;
ArrayList <Integer> likeArray = new ArrayList <Integer>();
for (int count = 0; count < likeArray.size();count++){
// Set Up Database Source
db.setUp("IT Innovation Project");
String sql = "Select likeDislike_likes from forumLikeDislike WHERE topic_id = "
+ topicId + "";
ResultSet resultSet = null;
// Call readRequest to get the result
resultSet = db.readRequest(sql);
try {
while (resultSet.next()) {
likeArray.add(Integer.parseInt(resultSet.getString("likeDislike_likes")));
likes += likeArray.get(count);
}
resultSet.close();
} catch (Exception e) {
System.out.println(e);
}
}
jLabel_like.setText(Integer.toString(likes));
}
However, it keeps returning 0. Thanks in advance.
(As an aside, it never returns anything - you've posted a void method.)
Look at this code:
ArrayList <Integer> likeArray = new ArrayList <Integer>();
for (int count = 0; count < likeArray.size();count++){
...
}
You've just created a new ArrayList<Integer>, which will therefore have a size of 0. Therefore, the loop always completes immediately, without ever executing the body.
If you're trying to get input from a list created elsewhere, you should probably pass that into your method. (You should also use a PreparedStatement with a parameter instead of including the value directly in your SQL.)
You're iterating over the list likeArray which is empty. So it won't enter the loop
May be here is the new code you should refer:
public void SetUpLikeAmount() {
int likes = 0;
// Set Up Database Source
db.setUp("IT Innovation Project");
String sql = "Select likeDislike_likes from forumLikeDislike WHERE topic_id = "
+ topicId + "";
ResultSet resultSet = null;
// Call readRequest to get the result
resultSet = db.readRequest(sql);
try {
while (resultSet.next()) {
likes += Integer.parseInt(resultSet.getString("likeDislike_likes"));
}
resultSet.close();
} catch (Exception e) {
System.out.println(e);
}
jLabel_like.setText(Integer.toString(likes));
}
You might not need the arraylist I believe as you are getting the value and summing it during the iteration over the result set only.

Categories