ArrayList<Objects[]> to strings to use in SQL IN statement - java

I am trying to build a string to pass it as an SQL query within the IN statement.
ArrayList<Object[]> arrayList = new ArrayList<Object[]>();
List<String> strings = new ArrayList<>(arrayList .size());
for (Object object : arrayList ) {
strings.add(Objects.toString(object, null));
}
System.out.println("askldnlkasdn"+strings);
This still prints out the memory locations instead of the actual string
askldnlkasdn[[Ljava.lang.Object;#7bb11784, [Ljava.lang.Object;#33a10788, [Ljava.lang.Object;#7006c658, [Ljava.lang.Object;#34033bd0, [Ljava.lang.Object;#47fd17e3, [Ljava.lang.Object;#7cdbc5d3, [Ljava.lang.Object;#3aa9e816, [Ljava.lang.Object;#17d99928, [Ljava.lang.Object;#3834d63f, [Ljava.lang.Object;#1ae369b7]
I have also tried out
using StringBuilder and StringUtils. But things dont seem to work.
Any inputs as to where the problem is?

you should override method toString in your objects

You can use an SQL specific java Array.
try (PreparedStatement stmt = connection.prepareStatement("... IN (?) ...")) {
Object[] elements = ...
stmt.setArray(1, connection.createArray("TEXT", elements));
stmt.executeUpdate();
}

The problem you have is that you are implicitly using the toString() method of the Object elements inside your ArrayList. By default, that method returns the class and address of the Object. You should override the toString() method in every class you will use inside the list so it returns what you want it to.

This is new code that may help,
// Data of Array of Object for test the Code
Object[] a = new Object[1];
a[0] = "Hello";
Object[] b = new Object[1];
b[0] = "Friend";
Object[] c = new Object[1];
c[0] = "This is";
Object[] d = new Object[1];
d[0] = "Just Test";
// The Array List of objects and the data entry
ArrayList<Object[]> arrayList = new ArrayList<Object[]>();
arrayList.add(a);
arrayList.add(b);
arrayList.add(c);
arrayList.add(d);
// New List of strings
List<String> strings = new ArrayList<>(arrayList .size());
// The Process of adding the data from array list of objects to the strings
for(int i = 0; i < arrayList.size(); i++){
strings.add((String) arrayList.get(i)[0]);
}
// Just for print the data to console
for(int i = 0 ; i < strings.size(); i++){
System.out.println(strings.get(i));
}
System.out.println("askldnlkasdn "+strings.get(0));
I hope that solve the problem, if not please inform me, you can use it for more than one dimensional array.

You can just save it as String , like this code
ArrayList<String> arrayList = new ArrayList<>();
List<String> strings = new ArrayList<>(arrayList .size());
for (Object object : arrayList ) {
strings.add(Objects.toString(object, null));
}
System.out.println("askldnlkasdn"+strings);
Or you want it Object for specific purpose?

Related

Convert ArrayList to List<GenericModel> gives ClassCastException

I am converting stored procedure to complete JPA query. One of the SP query is as below which i am converting to entity class. I am converting this to a bean defined as Generic model which results in classcastexception.
SP query whose result set rs4 in java class is as follows:
rs4 Query: select command_value as descr from SCAN_COMMAND_NAME
where command_name = 'AAA' ORDER BY SEQ;
Here the result set rs4 is converted to GenericModel:
ResultSet rs4 = (ResultSet) cs.getObject(cnt++);
List commandRotateLi = new BeanProcessor().toBeanList(rs4,GenericModel.class);
session.setAttribute("coRotate", commandRotateLi);
///...
..///
ArrayList coRotate = (ArrayList) session.getAttribute("coRotate");
for(int x = 0; x < coRotate.size(); x++){
gm = (GenericModel) coRotate.get(x);
///
}
This above code works fine. Below is JPA converted code.
List<ScanCommandName> scanCommandList = new ArrayList<ScanCommandName>();
query = em.createNamedQuery("ScanCommandName.findByCommandName", ScanCommandName.class);
query.setParameter("commandName", Constants.IMAGE_MAGICK_ROTATE);
scanCommandList = query.getResultList();
scanCommandList.toString() gives me 5 ScanCommandName objects. I have to convert this List to List and loop through as above one but struck at class cast exception in the for loop.
ArrayList list = new ArrayList();
List<GenericModel> coRotate = null;
for(int y=0; y<scanCommandList.size(); y++){
ScanCommandName s = scanCommandList.get(y);
list.add(s.getCommandValue());
}
coRotate = (List<GenericModel>) (List) list;
I am now looping through the List coRotate but getting classcast at the 1st line in for loop.
for(int x = 0; x < coRotate.size(); x++){
gm = (GenericModel) coRotate.get(x);
///
}
java.lang.ClassCastException: java.lang.String cannot be cast to com.GenericModel
Any suggestions highly appreciated. thank you.
This is essentially what you are doing:
ArrayList list = new ArrayList();
List<SomeClass> slist;
list.add("String"); // <-- I'm guessing here based on exception
slist = (List<SomeClass>) list;
for (SomeClass s : slist) { // class cast exception
System.out.println(s);
}
class SomeClass {
}
Had you done this:
ArrayList<String> list = new ArrayList<>();
You could not have done this
slist = (List<SomeClass>) list;
And the error would have been caught at compile time.
Without knowing the details of your class structure, I suspect that to do what you want, coRotate needs to hold instances of GenericModel and
your ArrayList needs to be declared as ArrayList<GenericModel> = new ArrayList<>()

JSON : Array & Compare

I have a set of JSON array :
listSession: [h0y78u93, h0y78u93, h0y78u93, h0y78u93, h0y78u93, 9i88u93, 9i88u93, 9i88u93, 9i88u93, 9i88u93]
I've created the array using the below code:
ArrayList<String> listSession = new ArrayList<String>();
for(int u=1; u < k+1; u++) {
String str = Integer.toString(u);
JSONArray arrTime=(JSONArray)mergedJSON2.get(str);
JSONObject objSession;
StringsessionName;
for (Object ro : arrTime) {
objSession = (JSONObject) ro;
sessionName = String.valueOf(objSession.get("sessionID"));
listSession.add(sessionName);
}
}
May I get your advice or opinion on how am I going to compare the value from each of the attributes in the list. If it is the same, I should it as ONE.
Meaning from the above sample, the count should be only TWO instead of TEN.
Thank You.
You can utilize Arraylist.contains() method like below:
ArrayList<String> listSession = new ArrayList<String>();
for(int u=1; u < k+1; u++) {
String str = Integer.toString(u);
JSONArray arrTime=(JSONArray)mergedJSON2.get(str);
JSONObject objSession;
StringsessionName;
for (Object ro : arrTime) {
objSession = (JSONObject) ro;
sessionName = String.valueOf(objSession.get("sessionID"));
if (!listSession.contains(sessionName)) {
listSession.add(sessionName);
}
}
}
OR
You can use a Set implementation which doesn't allow duplicate values instead of ArrayList. There's no need to compare explicitly.
// initialize
Set sessionsSet = new HashSet();
//add like below
sessionsSet.add(sessionName);
sessionsSet.size() // getting the length which should be what you expect to be 2
I would recommend to use a Set over ArrayList here. You can use ArrayList and check the list whether it contains the element and add it. ArrayList.contains() takes O(n) time because it maintains a dynamic array inside. Where as a HashSet or TreeSet can do that check in O(1) and you also don't have to do that compare yourself.
Set<String> setSession = new HashSet<String>();
for(int u=1; u < k+1; u++) {
String str = Integer.toString(u);
JSONArray arrTime=(JSONArray)mergedJSON2.get(str);
JSONObject objSession;
StringsessionName;
for (Object ro : arrTime) {
objSession = (JSONObject) ro;
sessionName = String.valueOf(objSession.get("sessionID"));
setSession.add(sessionName);
}
}
If you're okay using Java 8, then you can use shorthand implementation like this:
Example:
ArrayList<String> data = new ArrayList<String>(Arrays.asList("A", "A", "A", "B", "B", "B"));
// This will be required if your target SDK < Android N
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
List<String> uniqueData = data.stream().distinct().collect(Collectors.toList()); // Results ["A", "B"]
}

Swings: storing the selected values from List into an array.

I made a List in java as under:
String names[] = {"abc#gmail.com", "def#gmail.com","ghi#gmail.com","jkl#gmail.com"};
JList places = new JList(names) ;
Then in order to access the selected values I wrote in valueChanged method :
String[] emailID= places.getSelectedValuesList().toString[];
which is coming out to be incorrect ... Kindly help how should I rewrite this line so as the selected values get stored in array.
If you want to have all selected Items as an Array you can do something like this:
public static void main(String[] args){
String names[] = {"abc#gmail.com", "def#gmail.com","ghi#gmail.com","jkl#gmail.com"};
JList<String> places = new JList<String>(names) ;
places.setSelectedIndices(new int[]{0,1,2});
String[] emailIDs = places.getSelectedValuesList().toArray(new String[]{});
for(String s : emailIDs){
System.out.println(s);
}
}
Note:
I added <String> to the List, because I assume you always want to have Strings as values. That way you can get the List .toArray() method with a generic output. Else you'd need to get an Object[] (Object Array) and cast the values.
For Storing Selected Items in String Array you can try this
Object[] values = places.getSelectedValues();
String[] strings = new String[values.length];
for(int i = 0; i < values.length; i++) {
if(values[i] instanceof String) {
strings[i] = ((String) values[i]);
}
}

Object array issue

I wan to know why am I getting a null pointer exception on the line marked below, I am trying to add stuff from a properties table to the object map, so I can insert column information into a JTable dont know if its 100% clear, but any input will be appreciated
public Object getList(){
dvd.loadList(dvd.dvdInventory);
Object [][] data = null;
int i = 0;
int j = 0;
Iterator<Object> kitr= dvd.dvdInventory.keySet().iterator();
Iterator<Object> itr = dvd.dvdInventory.values().iterator();
while(itr.hasNext()){
String key = (String) kitr.next();
String values = (String) itr.next();
String[] tokens = values.split(" / ");
for ( String token : tokens ){
data[j][i] = token.toString(); <------this line gets null
i++; pointer exception
}
i = 0;
j++;
}
return data;
}
Object [][] data = null;
The array is null. YOu need to allocate space:
Object [][] data = new Object[5][5];
or whatever size you want.
Unless you know the size of the row/columns of the array it is better to use a Vector of Vectors for the DefaultTableModel of JTable.
Edit:
To use Vectors you would restructure the code to be something like:
Vector<Vector<String>> data = new Vector<Vector<String>>();
while(itr.hasNext())
{
String key = (String) kitr.next();
String values = (String) itr.next();
String[] tokens = values.split(" / ");
Vector<String> row = new Vector<String>();
for ( String token : tokens ){
row.add(token.toString());
}
data.add(row);
}
Null pointer exception is happening because you have initialized your array as null. You need to allocate some memory to your array, right now it is just null as defined here:
Object [][] data = null;
You should know, what size do you need to for the array that you have. You cannot simply initialize it to any value. If you don't know the size then consider using the collections, which can grow dynamically.
You may consider using List of Arraylist and define it as :
List<List<Object>> lists = new ArrayList<List<Object>>();

Sorting a list of maps within before this while loop runs out(Java)

A database call is made and result is a bunch of rows of two string columns of type A and B. e.g. (x_a, y_b), (x_a, y1_b), (x2_a,y_b)
The idea is to come up with a list of maps like {(x_a,{y_b,y1_b}), (x2_a,{y_b})} where the objects of type A are not repeated and to do this while pulling the results from a database.
Here's what I tried:
int i =0;
List<String> type2 = new ArrayList<String>();
Map<String,List<String>> type1_type2 = new HashMap<String,List<String>>();
List<Map> list_type1_type2 = new ArrayList<Map>();
String [] type1Array = new String[100];
String [] type2Array = new String[100];
int trackStart = 0;
while (res.next()){
String type1 = res.getString(1);
String type2 = res.getString(2);
type1Array[i]=type1;
type2Array[i] = type2;
if(i>0 && !type1Array[i].equals(type2Array[i-1])){
int trackStop = i;
for(int j = trackStart; j<trackStop;j++){
type2.add(type2Array[j]);
}
type1_type2.put(type1Array[i-1], type2);
list_type1_type2.add(type1_type2);
//debugging stuff
String x = list_type1_type2.toString();
System.out.println(x);
System.out.println(" printing because "+ type1Array[i]+" is not equal to " + type1Array[i-1]);
type2 = new ArrayList<String>();
type1_type2 = new HashMap<String,List<String>>();
trackStart=i;
}
i++;
}
This method does not work when the last type1 values of the result object are the same.
Is there a way to do this in the same spirit (within the while(res.next)) without first storing the results of the database call in separate arrays or adding an extra for loop outside the while loop to "patch it up"?
The simple way to do this is to use a Guava / Google Collections SetMultiMap. This is essentially a mapping from a key (your 'A' objects) to a set of values (your 'B' objects).
[I'm not going to try to code it for you. Your current code is too horrible to read ... unless you were paying me :-) ]
However, a better idea would be to get the database to do the collation. If you can do that, you will reduce the amount of (redundant) data that gets send across the database connection ... assuming that you are using JDBC.
If you don't want duplicates like {x_a:[y_b, y_b]} then use a set as the value of your map:
Map<String,Set<String>> type1_type2;
I don't know what the other various list and arrays are for. You can probably just get by with the type1_type2 map. Process each (x, y) in pseudo-code:
Set s = type1_type2.get(x)
if s == null:
s = new Set()
type1_type2.put(x, s)
s.add(y)

Categories

Resources