Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Iterate through List of Object arrays

Tags:

java

hibernate

So right now I have a program containing a piece of code that looks like this...

Criteria crit = session.createCriteria(Product.class);
ProjectionList projList = Projections.projectionList();
projList.add(Projections.max("price"));
projList.add(Projections.min("price"));
projList.add(Projections.countDistinct("description"));
crit.setProjection(projList);
List results = crit.list();

I want to iterate results.So thank you in advance for any help/advice that is offered.

like image 536
Naveen A Avatar asked Dec 22 '11 07:12

Naveen A


2 Answers

In this case you will have a list whose elements is an array of the following: [maxPrice,minPrice,count].

....
List<Object[]> results = crit.list();

for (Object[] result : results) {
    Integer maxPrice = (Integer)result[0];
    Integer minPrice = (Integer)result[1];
    Long count = (Long)result[2];
}
like image 161
Comrade Avatar answered Oct 22 '22 01:10

Comrade


You could use Generic in List and for each but for current code you could do following to iterate

for(int i = 0 ; i < results.size() ; i++){
 Foo foo = (Foo) results.get(i);

}

Or better to go for readable for-each loop

for(Foo foo: listOfFoos){
  // access foo here
}
like image 24
jmj Avatar answered Oct 22 '22 02:10

jmj