-1

I'm getting result as below after making query to database

VendorName | IncidentID | IncidentStatus | IncidentDate
-------------------------------------------------------
XYZ        | 100        |     Open       | 02-JUN-2011    
ABC        | 101        |     Closed     | 03-JUN-2011  
MNP        | 102        |     Open       | 01-JUN-2011  
LPQ        | 103        |     Open       | 01-APR-2011 

I'm iterating the list using following snippet of code

Iterator iter=resultList.iterator();
  while (iter.hasNext()) {
    Object[] result= (Object[]) iter.next();
    System.out.println("Vendor Name-->" +result[0]);
}

While iterating the list, I want to return only the Closed incident row. How to do this ?

I understand, it can be done by defining a new list and add one by one object to this but is there any better approach?

greedybuddha
  • 7,488
  • 3
  • 36
  • 50
Pankaj
  • 3,512
  • 16
  • 49
  • 83

4 Answers4

0

Why are you filtering the result set? It seems kinda unnecessary Why not just add "IncidentStatus == Closed" to your query?

elefont
  • 151
  • 1
  • 7
0

Here is a suggestion if you can't add the where IncidentStatus=closed to the sql.

//assume that Obj is one objet with the properties for this row
ArrayList<Obj> ret = new ArrayList<Obj>();
Iterator iter=resultList.iterator();
  while (iter.hasNext()) {
    Object[] result= (Object[]) iter.next();
    //check if the status is closed
    if(result[2].equals("Closed"){
         ret.add(new Obj(result[0],result[1],result[2],result[3]));
    }
}
fmodos
  • 4,472
  • 1
  • 16
  • 17
0

Well, first if it's posible it seems better to add the restriction when you query the database, otherwise I suggest you to use Apache Commons Collection FilterIterator

Predicate<Object[]> predicate = new Predicate<>() {
                   evaluate(Object[] obj) { 
                         return (obj[2].equals("Closed")); 
                   }
               };

Iterator<Object[]> filteredIterator = new FilterIterator<>(
                            resultList.iterator, 
                            predicate
                        );

This aproach allows you to create a generic table predicate class that helps you filter an iterator or a collection using any field and value.

jordeu
  • 6,711
  • 1
  • 19
  • 19
0

Assuming you are using java 1.7

if(resultList == null)
  return;

List<MyClass> toReturn = new ArrayList<>(resultList.size());

for(MyClass element : resultList){
  if (element.isClosedState()){
    toReturn.add(element);
  }
}

You can use external api.

lambdaj allows to filter collections without writing loops or inner classes as in the following example:

List<MyClass> elements = select(element, having(on(MyClass.class).getProperty(),
    greaterThan(someValue)));

guava or wait Java 8 release.

this link may help you what is the best wat to filter a collection

Community
  • 1
  • 1
nachokk
  • 14,363
  • 4
  • 24
  • 53