Searching in a ArrayList with custom objects for certain strings

前端 未结 9 634
感情败类
感情败类 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 myList = new ArrayList<>();
    //Fill up myList with your Data Points
    
    List 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 nameEqualsTo(final String name) {
        return new Predicate() {
    
            public boolean apply(DataPoint dataPoint) {
                return dataPoint.getName().equals(name);
            }
        };
    }
    
    public void main(String[] args) throws Exception {
    
        List myList = new ArrayList();
        //Fill up myList with your Data Points
    
        Collection dataPointsCalledJohn =
                Collections2.filter(myList, nameEqualsTo("john"));
    
    }
    

提交回复
热议问题