Searching in a ArrayList with custom objects for c

2020-01-27 13:54发布

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.

9条回答
爷、活的狠高调
2楼-- · 2020-01-27 14:31

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
}
}
查看更多
聊天终结者
3楼-- · 2020-01-27 14:38

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.

查看更多
乱世女痞
4楼-- · 2020-01-27 14:38
boolean found;

for(CustomObject obj : ArrayOfCustObj) {

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

      found = true;
   }
}
查看更多
不美不萌又怎样
5楼-- · 2020-01-27 14:41
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
      }    
   }
}
查看更多
6楼-- · 2020-01-27 14:42

Use Apache CollectionUtils:

CollectionUtils.find(myList, new Predicate() {
   public boolean evaluate(Object o) {
      return name.equals(((MyClass) o).getName());
   }
}
查看更多
女痞
7楼-- · 2020-01-27 14:48

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!");
     }
}
查看更多
登录 后发表回答