Filtering a list of JavaBeans with Google Guava

前端 未结 9 777
夕颜
夕颜 2020-12-01 06:59

In a Java program, I have a list of beans that I want to filter based on a specific property.

For example, say I have a list of Person, a JavaBean, where Person has

9条回答
  •  余生分开走
    2020-12-01 07:19

    Here is an example of using generics using guava, beanutils to filter any list using requested match

    /**
     * Filter List
     * 
     * @param inputList
     * @param requestMatch
     * @param invokeMethod
     * @return
     */
    public static  Iterable predicateFilterList(List inputList, final String requestMatch,
            final String invokeMethod) {
        Predicate filtered = new Predicate() {
            @Override
            public boolean apply(T input) {
                boolean ok = false;
                try {
                    ok = BeanUtils.getProperty(input, invokeMethod).equalsIgnoreCase(requestMatch);
                }
                catch (Exception e) {
                    e.printStackTrace();
                }
                return ok;
            }
        };
        return Iterables.filter(inputList, filtered);
    }
    

提交回复
热议问题