JAVA中对List进行查询

JAVA中从数据库中取数据,根据MyBits返回结果主要有两种类型的List,一种是List,还一种是List>,

那么怎样对List结果集进行查询操作呢?当然最常用的是用for循环遍历,但是这个效率比较低下,下面是我认为比较好的操作方式,

对List>的查询

    /**
     * 从列表中找出包括Value值的列表
     * @param list
     * @param keyName
     * @param value
     * @return
     */
    public static List> findDataFromListMap(List> list,String keyName,Object value) {

        Predicate>predicate = new Predicate>() {

            @Override
            public boolean evaluate(Map map) {
                // TODO Auto-generated method stub
                try {
                    Object val = map.get(keyName);
                    if(value == null || val == null)
                        return false;

                    return val.equals(value);
                }
                catch (Exception e) {
                    return false;
                }
            }
        };

        List> result = (List>) CollectionUtils.select( list, predicate);
        return result;
    }

    /**
     * 多值将交叉查找
     * @param list
     * @param keyName2ValueMap
     * @return
     */
    public static List> findDataFromListMapByKeyValues(
            List> list,
            Map keyName2ValueMap) {

        Predicate>predicate = new Predicate>() {

            @Override
            public boolean evaluate(Map map) {
                // TODO Auto-generated method stub
                try {
                    for(Map.Entry entry : keyName2ValueMap.entrySet()){
                        String keyName  = entry.getKey();
                        Object value = entry.getValue();
                        Object val = map.get(keyName);
                        if(StringUtils.isBlank(keyName) || value == null || val == null)
                            return false;
                        if(!val.equals(value))
                            return  false;
                    }
                    return true;
                }
                catch (Exception e) {
                    return false;
                }
            }
        };

        List> result = (List>) CollectionUtils.select( list, predicate);
        return result;
    }

对List的查询

    /**
     * 从列表中找出包括Value值的对象列表
     * @param list
     * @param methodName
     * @param value
     * @return
     */
    public static  List findObjFromList(List list,String methodName,V value) {
    	
    	Predicatepredicate = new Predicate() {

			@Override
			public boolean evaluate(T obj) {
				// TODO Auto-generated method stub
				try {
					Method method = obj.getClass().getMethod(methodName);
					@SuppressWarnings("unchecked")
					V keyName = (V) method.invoke(obj);
					return keyName.equals(value);
				}
				catch (Exception e) {
					return false;
				}
			}
		};
		
		List result = (List) CollectionUtils.select( list, predicate);
		return result;
    		
    }

 

你可能感兴趣的:(JAVA)