Searching in a ArrayList with custom objects for certain strings

前端 未结 9 576
感情败类
感情败类 2020-12-01 02:09

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 Da         


        
相关标签:
9条回答
  • 2020-12-01 02:11

    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"));
    
    }
    
    0 讨论(0)
  • 2020-12-01 02:14

    Use Apache CollectionUtils:

    CollectionUtils.find(myList, new Predicate() {
       public boolean evaluate(Object o) {
          return name.equals(((MyClass) o).getName());
       }
    }
    
    0 讨论(0)
  • 2020-12-01 02:16

    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!");
         }
    }
    
    0 讨论(0)
  • 2020-12-01 02:19
    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
          }    
       }
    }
    
    0 讨论(0)
  • 2020-12-01 02:24

    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
    }
    }
    
    0 讨论(0)
  • 2020-12-01 02:27

    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.

    0 讨论(0)
提交回复
热议问题