private User findUserByName(List<User> userList, final String name) {
Optional<User> userOptional =
FluentIterable.from(userList).firstMatch(new Predicate<User>() {
@Override
public boolean apply(@Nullable User input) {
return input.getName().equals(name);
}
});
return userOptional.isPresent() ? userOptional.get() : null; // return user if found otherwise return null if user name don't exist in user list
}
private final Optional<Carnet> findCarnet(Collection<Carnet> yourList, String codeIsin){
// This stream will simply return any carnet that matches the filter. It will be wrapped in a Optional object.
// If no carnets are matched, an "Optional.empty" item will be returned
return yourList.stream().filter(c -> c.getCodeIsin().equals(codeIsin)).findAny();
}
Now a usage for it:
public void yourMethod(String codeIsin){
List<Carnet> listCarnet = carnetEJB.findAll();
Optional<Carnet> carnetFound = findCarnet(listCarnet, codeIsin);
if(carnetFound.isPresent()){
// You use this ".get()" method to actually get your carnet from the Optional object
doSomething(carnetFound.get());
}
else{
doSomethingElse();
}
}
//Search into a generic list ALL items with a generic property
public final class SearchTools {
public static <T> List<T> findByProperty(Collection<T> col, Predicate<T> filter) {
List<T> filteredList = (List<T>) col.stream().filter(filter).collect(Collectors.toList());
return filteredList;
}
//Search in the list "listItems" ALL items of type "Item" with the specific property "iD_item=itemID"
public static final class ItemTools {
public static List<Item> findByItemID(Collection<Item> listItems, String itemID) {
return SearchTools.findByProperty(listItems, item -> itemID.equals(item.getiD_Item()));
}
}
}
类似地,如果希望使用某个属性过滤 HashMap中的 ALL项
//Search into a MAP ALL items with a given property
public final class SearchTools {
public static <T> HashMap<String,T> filterByProperty(HashMap<String,T> completeMap, Predicate<? super Map.Entry<String,T>> filter) {
HashMap<String,T> filteredList = (HashMap<String,T>) completeMap.entrySet().stream()
.filter(filter)
.collect(Collectors.toMap(map -> map.getKey(), map -> map.getValue()));
return filteredList;
}
//Search into the MAP ALL items with specific properties
public static final class ItemTools {
public static HashMap<String,Item> filterByParentID(HashMap<String,Item> mapItems, String parentID) {
return SearchTools.filterByProperty(mapItems, mapItem -> parentID.equals(mapItem.getValue().getiD_Parent()));
}
public static HashMap<String,Item> filterBySciName(HashMap<String,Item> mapItems, String sciName) {
return SearchTools.filterByProperty(mapItems, mapItem -> sciName.equals(mapItem.getValue().getSciName()));
}
}