13

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.

1
  • If this is schoolwork tag it as such. Otherwise, List<Product> results = crit.list(); and then for (Product p: results) {} Commented Dec 22, 2011 at 7:47

3 Answers 3

22

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];
}
Sign up to request clarification or add additional context in comments.

Comments

5

You can probably do something like this:

for (Object result : results) {
    // process each result
}

Comments

5

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
}

3 Comments

Or maybe use an iterator if you want to be slightly more modern? like for (Iterator<Product> pi = results.iterator(); pi.hasNext();) { Product p = pi.next();}
Yeah, but this solution is old school and low-tech! Who couldn't possibly like it?
It is not possible to cast (object[]) object array to a object like Foo

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.