I have a problem with downloading the first object in the list that meets the condition.
My code always returns the first object that is on the list, regardless of condition. Returns the person with id = 1.
main(){
public static void main(String args[]) {
List<Person> persons = Lists.newArrayList();
persons.add(new Person("1", "aaa",23, true));
persons.add(new Person("2", "bbb",16, false));
persons.add(new Person("3", "ccc",56, true));
Person per = (Person) Iterables.getFirst(persons, new Predicate<Person>() {
@Override
public boolean apply(Person person) {
return person.getAge()> 50;
}
});
System.out.println(per.getId()); // always "1"
}
public class Person {
private String id;
private String name;
private int age;
private boolean isSome;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public boolean isSome() {
return isSome;
}
public void setSome(boolean isPaid) {
this.isSome = isPaid;
}
public Person(){}
public Person(String id, String name, int age, boolean isSome){
this.id = id;
this.name = name;
this.age = age;
this.isSome = isSome;
}
}
Could someone explain why this is happening and how to deal with it?
We can find the first element of an array that satisfies a given condition using the first(where:) method.
Get the first element of ArrayList with use of get(index) method by passing index = 0. Get the last element of ArrayList with use of get(index) method by passing index = size – 1.
The first element of a list can be modified, unlike an Iterable. A list. first is equivalent to list[0] , both for getting and setting the value. final numbers = <int>[1, 2, 3]; print(numbers.
Iterables.getFirst()
doesn't do what you think it does. You should be using Iterables.tryFind()
method, which returns the first matching element in the iterable passed. It returns an Optional<T>
, so you need to invoke get()
on the result, or Optional#or()
, if you want some default value.
Person per = Iterables.tryFind(persons, new Predicate<Person>() {
@Override
public boolean apply(Person person) {
return person.getAge()> 50;
}
}).or(defaultPerson);
Though you are attempting to solve this using guava you might be interested in how this can be done in java8:
List<Person> persons = Lists.newArrayList();
persons.add(new Person("1", "aaa",23, true));
persons.add(new Person("2", "bbb",16, false));
persons.add(new Person("3", "ccc",56, true));
Person per = persons.stream().filter(p -> p.getAge() > 50).findFirst().get();
System.out.println(per.getId());
findFirst will return an Optional<Person>
for the sake of brevity I called get on it, but be aware that get will return null should nothing match the predicate of getAge > 50
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With