[java] Searching in a ArrayList with custom objects for certain strings

I have a ArrayList with custom objects. I want to search inside this ArrayList for Strings.

The class for the objects look like this:

public class Datapoint implements Serializable {

  private String stateBased;
  private String name;
  private String priority;
  private String mainNumber;
  private String groupadress;
  private String dptID;

  public Datapoint(){
  }

  public String getMainNumber() {
    return mainNumber;
  }

  public void setMainNumber(String mainNumber) {
    this.mainNumber = mainNumber;
  }

  public String getName() {
    return name;
  }

  ..and so on

I know how to search for a string in a ArrayList but how to do that in a ArrayList with my custom objects:

ArrayList<String> searchList = new ArrayList<String>();
String search = "a";
int searchListLength = searchList.size();
for (int i = 0; i < searchListLength; i++) {
if (searchList.get(i).contains(search)) {
//Do whatever you want here
}
}

So I want to have a function to search in my ArrayList with for example five objects for all "name" strings.

This question is related to java search arraylist custom-object

The answer is


For a custom class to work properly in collections you'll have to implement/override the equals() methods of the class. For sorting also override compareTo().

See this article or google about how to implement those methods properly.


UPDATE: Using Java 8 Syntax

List<DataPoint> myList = new ArrayList<>();
//Fill up myList with your Data Points

List<DataPoint> dataPointsCalledJohn = 
    myList
    .stream()
    .filter(p-> p.getName().equals(("john")))
    .collect(Collectors.toList());

If you don't mind using an external libaray - you can use Predicates from the Google Guava library as follows:

class DataPoint {
    String name;

    String getName() { return name; }
}

Predicate<DataPoint> nameEqualsTo(final String name) {
    return new Predicate<DataPoint>() {

        public boolean apply(DataPoint dataPoint) {
            return dataPoint.getName().equals(name);
        }
    };
}

public void main(String[] args) throws Exception {

    List<DataPoint> myList = new ArrayList<DataPoint>();
    //Fill up myList with your Data Points

    Collection<DataPoint> dataPointsCalledJohn =
            Collections2.filter(myList, nameEqualsTo("john"));

}

try this

ArrayList<Datapoint > searchList = new ArrayList<Datapoint >();
String search = "a";
int searchListLength = searchList.size();
for (int i = 0; i < searchListLength; i++) {
if (searchList.get(i).getName().contains(search)) {
//Do whatever you want here
}
}

contains() method just calls equals() on ArrayList elements, so you can overload your class's equals() based on the name class variable. Return true from equals() if name is equal to the matching String. Hope this helps.


Use Apache CollectionUtils:

CollectionUtils.find(myList, new Predicate() {
   public boolean evaluate(Object o) {
      return name.equals(((MyClass) o).getName());
   }
}

Probably something like:

ArrayList<DataPoint> myList = new ArrayList<DataPoint>();
//Fill up myList with your Data Points

//Traversal
for(DataPoint myPoint : myList) {
    if(myPoint.getName() != null && myPoint.getName().equals("Michael Hoffmann")) {
        //Process data do whatever you want
        System.out.println("Found it!");
     }
}

String string;
for (Datapoint d : dataPointList) {    
   Field[] fields = d.getFields();
   for (Field f : fields) {
      String value = (String) g.get(d);
      if (value.equals(string)) {
         //Do your stuff
      }    
   }
}

boolean found;

for(CustomObject obj : ArrayOfCustObj) {

   if(obj.getName.equals("Android")) {

      found = true;
   }
}

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log Find a file by name in Visual Studio Code Search all the occurrences of a string in the entire project in Android Studio Java List.contains(Object with field value equal to x) Trigger an action after selection select2 How can I search for a commit message on GitHub? SQL search multiple values in same field Find a string by searching all tables in SQL Server Management Studio 2008 Search File And Find Exact Match And Print Line? Java - Search for files in a directory How to put a delay on AngularJS instant search?

Examples related to arraylist

Adding null values to arraylist How to iterate through an ArrayList of Objects of ArrayList of Objects? Dynamically adding elements to ArrayList in Groovy How to replace existing value of ArrayList element in Java How to remove the last element added into the List? How to append elements at the end of ArrayList in Java? Removing Duplicate Values from ArrayList How to declare an ArrayList with values? In Java, can you modify a List while iterating through it? Load arrayList data into JTable

Examples related to custom-object

Searching in a ArrayList with custom objects for certain strings