how to add a list to another list while looping? - java

I have a list which has object(record) taken from database. I need to add it another list of generic class inside a loop.When ever loop executes the final list contains only the last element.my coding are..
List<modelclass> mdlclasslist=new ArrayList();
for(Class_1 a:class1list) {
Query qr=s.createQuery("from Class_2 where ID= :f and code= :j order by mark desc");
qr.setParameter("f",id);
qr.setParameter("j",code);
List<Class_2> b=new ArrayList();
b=qr.list();
for(Class_2 cls:b) {
modelclass mdl=new modelclass(cls.getID(),cls.getCode(),cls.getMark());
mdlclasslist.add(mdl);
}
}
mdlclasslist contains same object.It is not adding every object the query takes.please advice.

Your Query appears to return the same list over and over again for every Class_1 item because id and code never change. I assuming your code should rather look like this:
Query qr=s.createQuery("from Class_2 where ID= :f and code= :j order by mark desc");
for( Class_1 a : class1list )
{
qr.setParameter( "f", a.id );
qr.setParameter( "j", a.code );
for( Class_2 cls: qr.list() )
{
modelclass mdl=new modelclass(cls.getID(),cls.getCode(),cls.getMark());
mdlclasslist.add(mdl);
}
}

How about debugging and printing out the number of elements in the 2nd list before adding?
Not sure if you want to append the List you retrieve from a DB to the one you initialize beforehand...
However, I would define the 1st List to be of the generic type Class_1 (BTW: read about Java naming conventions) and then use addAll
yourList.addAll(theListFromDB);

try this
listInstance.addAll(anotherListInstavce) ;

First i would check if my source list, the one populated from DB has more than 1 element. If you are using JDBC, its a very common mistake to not move the result set objects further.
Secondly if you need such collection manipulation utilities i suggest take a look at commons-collections ListUtils class.

All the collections have a simple method to add data of one collection to other.
list2.addAll(list1);
You can simply use this method...

Related

Fetching and modifying an object in a set in Java

I have MyFinalSalad class consisting of the following elements:
AppleClass apple;
BananaClass banana;
PearClass pear;
List<SpicesClass> spices;
I have equals implemented such as 2 MyFinalSalad objects are equal, if they have same AppleClass, BananaClass, PearClass objects in them.
Now, I am creating a set of MyFinalSalad objects.
And I have the following code:
MyFinalSalad mySalad = new MyFinalSalad(apple, banana, pear);
SpiceClass cinnamon = new SpiceClass("cinnamon");
if (mySet.contains(mySalad)) {
// I want to fetch mySalad object in the set and add cinnamon to the list of spices
} else {
List<SpiceClass> spices = new ArrayList<>();
spices.add(cinnamon);
mySalad.setSpices(spices);
mySet.add(mySalad);
}
To summarize, if mySalad is already present in mySet, add the spice object to the list of spices in mySalad from mySet, else add mySalad to mySet after creating a new spice list, adding cinnamon to it and inserting list in mySalad.
My question is, if set already has mySalad and I want to add a new spice to the list in that object, how do I achieve it?
From https://stackoverflow.com/a/7283419/887235 I have the following:
mySet.stream().filter(mySalad::equals).findAny().orElse(null).getSpices().add(cinnamon);
Is this the only way or the right way to do it? Or is there a better way?
I was thinking that as I am already entering if after doing a contains check, orElse(null) will never be encountered. Thus null.getSpices() will never occur. Is this assumption correct?
Is there a better way to do it?
I cannot change Set to Map.
Your assumption is correct. The orElse(null) will never take place since you check if the set contains the salad right before. You could replace it with get().
However, I would also go one level before and handle it as an Optional, taking the advantage of isPresent and get method.
Salad mySalad = new Salad();
Optional<Salad> possibleSalad = set.stream().filter(mySalad::equals).findAny();
if (possibleSalad.isPresent()) {
Salad alreadyExistingSalad = possibleSalad.get();
// combine spices
} else {
// add new salad
}

ParseQuery: convert from list of prices in database to strings android

​Hi All,
I am trying to build a scrolling custom listview that displays a list of products ordered by Price ascending. However I just realized I was storing the prices as strings which means $1000.00 comes before $2.01 because it is a character and not a number. I have converted my data to a "Number" on Parse and believe the best type to retrieve it is a double (can anyone comment on that for dollar amounts). The problem is I need to keep it as a number convert it to a string and then pass it to the listview for display on a text field. Initially i had
PPI.setProductprice((String) product.get("Price"));
like this:
// Locate the class table named "Products" in Parse.com
ParseQuery<ParseObject> query = new ParseQuery<ParseObject>(
"Products");
// Locate the column named "Price" in Parse.com and order list
// by ascending
query.orderByAscending("Price");
ob = query.find();
for (ParseObject product : ob) {
// Locate images in PrimaryPhoto column
ParseFile productimage = (ParseFile) product.get("PrimaryPhoto");
ProductPopulation PPI = new ProductPopulation();
PPI.setProductname((String) product.get("Name"));
PPI.setProductbrand((String) product.get("Brand"));
PPI.setProductprice((String) product.get("Price"));
PPI.setProductimage(productimage.getUrl());
productpopulationlist.add(PPI);
I then tried putting it into an array of doubles an iterating through it to convert to strings.
My last attempt which probably doesn't make sense was to change it like this:
PPI.setProductprice((Double) product.getDouble("Price"));
I am fairly knew to Android and any help you can give me would be appreciated.
Thanks in advance.
OK so i do not get the context here but what you can do is save the price as a string and when extracting it you could call Integer.parseInt(String intvalue); on the string to convert the value back to int then you can do all operations you ought to do. you can get a disordered array from the server and arrange it at device level that will save you some time and logic.
I don't know what is the ProductPopulation class you use to populate the list, so I can not say what exactly is the best way in your case, but in general a list can be ordered by means of the Collections.sort() method (see the method documentation).
You could sort the list before you add it to your list view. To sort a list the way you need, you must provide a comparator, than obtains the required values (fields or method results) from the objects that comprise your list, compares the obtained values and returns -1, 0, or 1, depending on the comparison result.
It could look somewhat like this:
for (...) {
ItemClass newObject = new ItemClass(); // new list item
// ...here add the values to the list item...
theList.add(newObject); // add the new item to the list
}
// now sort the list before adding it to the list viewer
Collections.sort(theList, new Comparator<ItemClass>() {
#Override
public int compare(ItemClass o1, ItemClass o2) {
// obtain and compare the values you need
return Double.compare(o1.getDouble(), o1.getDouble());
// you could also do something like
// Double.compare(
// Double.parseDouble(o1.getString()),
// Double.parseDouble(o2.getString()));
// but it would be much slower
}
});
// now add the sorted list to the viewer
listViewer.setList(theList);

ConcurrentModificationExample and possible code simplification

I am throwing a ConcurrentModificationExample in the following code. I checked the API and it has to do with me trying to modify an object while another thread is iterating over it. I am clueless on the matter. I have created a comment above the line causing the exception. The Employee class doesn't contain anything other than the three variables for storing information.
I will be including the entire class as I would also like to know if there is a way to simplify my code as it repeats many things such as object creation and adding everything to the lists.
When you call employeesByAge in here with dep.employees:
dep.employeesByAge(dep.employees)
that will pass in dep.employees to employeesByAge such that in:
public class Department{
LinkedList<Employee> employees = ...;
public LinkedList<Employee> employeesByAge(LinkedList<Employee> outputList) {
...
}
}
both the employee member field and the outputList parameter refers to the same list, not just two list with the same content, but the same list instance.
Then you do:
for (Employee emp: employees){
//the list is null. add the first employee
if (outputList.isEmpty()){
outputList.add(emp);
} else
...
}
which iterates the employee and modifies outputList, but remember that these two are the same list object. Thus, ConcurrentModificationException.
What you're attempting to do is similar to this...
List list = ...;
for(item: list) {
list.add(item);
}
That is, you're updating a collection with elements by iterating over the same collection. All
outputList.add(...);
in Department are adding elements to the collection from the same collection 'employees'.
In main(), by doing
dep.employeesByAge(dep.employees)
you're attempting to update 'dep.employees' with 'dep.employees.' which results in concurrent modification exception.

Drools: how to iterate list and add to another list

I am trying to iterate a ArrayList and add to another ArrayList using jboss drools inside the rule.
I have a pojo with the list.
Class DroolsPojo{
List<String> answers;
//getters and setters
}
My pojo returning a list like {"a","b","c","","",""}. I want to iterate the list and want to add elements which are not equal to ""(not empty elements of the list).
How can I do this with drools?
Is there any way to get the element count which is not equal to "" with the drools.
My rule is like as follows.
rule "rule1"
when
dpojo:DroolsPojo(answers!=null)
then
List list = dpojo.getAnswers();
//want to iterate the list here
end
How to do this with drools?
So the rule just has to fire when the answers instance variable is not null?
Using dialect mvel, something like this should work:
package drools.xxx
dialect "mvel"
import drools.xxx.DroolsPojo
rule "rule1"
when
$dpojo : DroolsPojo(answers!=null)
$answersWithoutEmptyStrings : List() from collect ( String(length > 0) from $dpojo.answers )
then
insert($answersWithoutEmptyStrings)
end
Here I do the collect (iterating) in the when clause.
On the right hand side you just write plain old Java code:
List list = dpojo.getAnswers();
for( Object obj: list ){
String s = (String)obj;
if( s.length() > 0 ){ ... }
}
The parser doesn't like generics (yet?) so you'll have to work around that.

How to "join" Hashtables in Java?

I have two strings:
A { 1,2,3,4,5,6 }
B { 6,7,8,9,10,11 }
it doesnt really matter what the numbers are in the strings. So then the user is going to pick what to join:
A hashjoin A.a1 = B.b5 B
I think I put the A into a hashtable by the A.a1 as the key and then iterate through B? The keys will be what the user wants then to join on and the data will be whats in the strings.
Are you sure you're trying to join hashtables? Perhaps you have the wrong data structure?
Look into java.util.Set (and java.util.HashSet). If you want the items that are in both tables, then it's a simple Set operation like so:
Collection A = new ...
...fill the A up...
Collection B = new ...
...fill the B up...
Set join = new HashSet();
join.addAll(A);
join.retainAll(B);
If you mean something more like a SQL table join, then the output will depend on what type of join you mean to perform, and what the equals sign means in this case. Note you'll have to write a Pair class (which you should make more descriptive than Pair for your exact case)
For a full join:
ArrayList pairs = new ArrayList();
for (Number numberA : A) {
for (Number numberB : B) {
pairs.add(new Pair(numberA, numberB));
}
}
For a full join with a where clause:
ArrayList pairs = new ArrayList();
for (Number numberA : A) {
for (Number numberB : B) {
if (check the condition of the where clause here) {
pairs.add(new Pair(numberA, numberB));
}
}
}
That's about as good an answer that can be given under the circumstances, as your question isn't very specific. If these general answers don't help you out, then you'll need to explain your question in more detail to get a more detailed answer.
--- First Edit, after some clarification ---
Ok, so it's an SQL-like equi-join.
Hashtables are Maps, which means they have an element in one "domain" which can be used to look up an element in another "domain". In a hash table, the first domain is the set of keys, and the second domain is the set of values. Think of it as a bunch of labels and a bunch of items. If the equi-join is to be performed, it must join like elements. That means it will either join one key to another key, or it will join one value to another value.
For keys:
Hashtable A = ...
Hashtable B = ...
Set keyJoin = new HashSet();
keyJoin.addAll(A.keySet());
keyJoin.retainAll(B.keySet());
For values:
Hashtable A = ...
Hashtable B = ...
Set valueJoin = new HashSet();
valueJoin.addAll(A.values());
valueJoin.retainAll(B.values());
It doesn't make sense to join the hashtables themselves; because, one "matching" value may live in both hashtables but be referenced by two different keys. Likewise, one "matching" key found in two different hashtables might not refer to the same value.
Your question doesn't make much sense. A hashtable (or hashmap), stores data as keys and values. You've said nothing about which of those values should be keys, and which should be values.

Categories