70

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.

Renato Lochetti
  • 4,558
  • 3
  • 32
  • 49
Mokkapps
  • 2,028
  • 9
  • 42
  • 67

9 Answers9

110

The easy way is to make a for where you verify if the atrrtibute name of the custom object have the desired string

    for(Datapoint d : dataPointList){
        if(d.getName() != null && d.getName().contains(search))
           //something here
    }

I think this helps you.

Renato Lochetti
  • 4,558
  • 3
  • 32
  • 49
  • also tried this one, but it does not find my String. If i convert my ArrayList to String it looks like this `[[[true] [Wippe links oben] [1] [1.001] [Low] [1 ]], [[true] [Wippe rechts] [1] [1.001] [Low] [2 ]], [[true] [Temperaturwert] [7] [7.001] [Low] [256 ]], [[true] [Schalten (Status)] [1] [1.001] [Low] [257 ]]]` – Mokkapps Sep 19 '12 at 14:02
  • What is the String that you want to find in that example? – Renato Lochetti Sep 19 '12 at 14:04
  • Ok. The code i posted only searchs for the name Attribute. You can add other verifications inside te IF clause. Like: `d.getMainNumber().contains...` This will solve the problem, but is not a beautifull solution. Will the attributes change in a future? – Renato Lochetti Sep 19 '12 at 14:06
  • ah of course.... the attributes are always the same, so I will implement six if clauses and that should solve my problem. Do you know a better or more beautiful solution? How can I find out the attribute "Name" for my "MainNumber"? – Mokkapps Sep 19 '12 at 14:10
  • 2
    You can implement a method inside the Datapoint class that do the verifications in all attributes. This way, you just call this method at the IF and it will return if the object has the desired string at one attribute or not. Other solution is to use Reflection and get all the methods, but i think this is over kill. – Renato Lochetti Sep 19 '12 at 14:12
44

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"));

}
munyengm
  • 15,029
  • 4
  • 24
  • 34
8

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
}
}
G_S
  • 7,068
  • 2
  • 21
  • 51
  • 1
    Possible NullPointerException if getName() is not set up. – gtgaxiola Sep 19 '12 at 13:47
  • 1
    just thinking that each and every value for the particular object are set. – G_S Sep 19 '12 at 13:48
  • If i convert my ArrayList to String it looks like this `[[[true] [Wippe links oben] [1] [1.001] [Low] [1 ]], [[true] [Wippe rechts] [1] [1.001] [Low] [2 ]], [[true] [Temperaturwert] [7] [7.001] [Low] [256 ]], [[true] [Schalten (Status)] [1] [1.001] [Low] [257 ]]]` . If I use for example `String search = "1.001";` it does not find any string... do you have a idea? – – Mokkapps Sep 19 '12 at 14:05
  • why are you converting it to a string? Are you interested to find whether the string search is in your arraylist irrespective of whether it is in stateBased or name or priority or mainNumber or groupadress or dptID? – G_S Sep 19 '12 at 15:53
5

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!");
     }
}
gtgaxiola
  • 9,241
  • 5
  • 42
  • 64
5

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.

Ridcully
  • 23,362
  • 7
  • 71
  • 86
3

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.

Egor
  • 39,695
  • 10
  • 113
  • 130
1

Use Apache CollectionUtils:

CollectionUtils.find(myList, new Predicate() {
   public boolean evaluate(Object o) {
      return name.equals(((MyClass) o).getName());
   }
}
developer033
  • 24,267
  • 8
  • 82
  • 108
MukeshKoshyM
  • 514
  • 1
  • 8
  • 16
0
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
      }    
   }
}
developer033
  • 24,267
  • 8
  • 82
  • 108
Artem Zelinskiy
  • 2,201
  • 16
  • 19
0
boolean found;

for(CustomObject obj : ArrayOfCustObj) {

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

      found = true;
   }
}
Sayali Shinde
  • 311
  • 2
  • 6