Boris Petrov
Boris Petrov

Reputation: 13

retrieving data from db with java streams

I am very new to Java 8 features like streams, filters and stuff and the tell the truth, I haven't been writing in Java for more than a year. Here is my problem if someone could give a suggestion .

@Override
public ArrayList<Agent> getAllEnabledAgents() throws Exception {    
    ArrayList<Agent> agents = repository.all(); //redis repository
    Stream<Agent> result = agents.stream().filter(a-> a.equals(a.getConfigState().Enabled));    //enum  
    return result; //I dont know how to return result or whether I am using stream correctly.

}

The main idea is that I want return all enabled agents. gerConfigState() returns an enum (__ConfigState). not sure If am doing this correctly.

Upvotes: 0

Views: 845

Answers (3)

Boris Petrov
Boris Petrov

Reputation: 13

Thanks for the help. This is the final version:

@Override
public List<Agent> getAllEnabledAgents() throws Exception {
      return repository.all()
            .stream()
            .filter(a-> a.getConfigState() == ConfigState.Enabled)
            .collect(Collectors.toList());
}

Upvotes: 0

Vijay
Vijay

Reputation: 552

Your filter condition is not correct (I assume getConfigState() returns an enum). You can use something like below:

Stream<Agent> streamAgent = agents.stream().filter(a-> a.getConfigState() == Enabled);    
return streamAgent.collect(Collectors.toList()); 

Upvotes: 1

Tobb
Tobb

Reputation: 12180

Use the collect-metod of the Stream. Also, your filter looks a bit strange, since the variable a is an object of class Agent.

So perhaps something like this:

agents.stream()
      .filter(a -> a.getConfigState() == Enabled)
      .collect(Collectors.toList());

Then again, like the comment states, you might just be better off filtering this with a query.

Upvotes: 1

Related Questions