Does Java have something similar to a list compiler of the C ++ standard library for finding an object by a variable?

In Java, is there something similar to C ++ standard library listings that use a comparator to search for a specific object in the list of one of its variables?

For example, instead of iterating over an ArrayList looking for a specific object, checking for a comparison of variables. Is there a way to use a comparator object to search for a specific instance?

(Note: I do not want to use hashmap, as this would create two separate lists. I want the functionality of the list not to be associated with the use of hashmap.)

Something like this, but for Java:

#include <algorithm>

using namespace std;

class Cperson     
{    
  string lastname, firstname, address, city;    
  int zipcode;    
  char state[3];    
  // this works for the last name    
  friend bool operator==(const Cperson& left, const Cperson& right);    
  friend bool firstEqualTo(const Cperson& left, const Cperson& right);    
};

bool operator==(const Cperson& left, const Cperson& right)    
{    
  return left.lastname == right.lastname;    
}

bool firstEqualTo(const Cperson& left, const Cperson& right)    
{    
  return left.firstname == right.firstname;    
}     

Now we can search our private list in the firstname field, ignoring the other fields:

vector<Cperson> personlist;    
// fill personlist somehow

Cperson searchFor;   // should contain the firstname we want to find    
vector<Cperson>::iterator fperson;   
fperson= std::find(personlist.begin(),    
                   personlist.end(),   
                   searchFor,    
                   firstEqualTo);
+3
source share
5

Google Guava, : guava

Update:

Google , , , Apache Commons Collections CollectionUtils:

List<Person> filteredList = new ArrayList<Person>(allPersons);
CollectionUtils.filter( filteredList, new Predicate() {
  boolean evaluate(Object object) {
    //do whatever you want
  }
});

, Commons Collections Generics. Commons Collections 3.1.

+3

java.lang.Comparable .

+1

, Java (. ) STL ++. equals .

, mySet.contains(o), , .

Java, , Person - equals true . , "" .

, , equals, hashCode.

0

list.contains (o);

, .

, . , ++:

for (Person p: persons) {
  if (p.firstname.equals ("John")) {  
     doSomethingWith (p);
     // if you only want to handle one case, the first John:
     break; 
  }
}

"John" -Collection:

List <Person> johns = ArrayList <Person> ();
for (Person p: persons) {
  if (p.firstname.equals ("John")) {  
     johns.add (p);
  }
}
0

All Articles