List<Integer> idList; 如果向集合增加 字符串“name”,会编译错误。

最近遇到了新鲜的问题,把集合 List<User> 中 user对象的 id抽取出来。

 User中的id字段是 String类型,但存的都是数字,因此想用泛型类型

List<Integer>接收。

语法没有报错。

但是在 遍历时,

for(Integer id: idList){
   
}

却提示 字符串不能强制转换为 Integer。

 

有兴趣的可以研究下,以下代码。

List<Integer>集合。

输出结果:[name, name2]

import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.beanutils.converters.*;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

/**
 * fansunion 
 * java王牌工具类 2017年12月27日
 */
@SuppressWarnings("unchecked")
public class JavaKit {

    /**
     * 提取集合中的对象的一个属性, 组合成List.
     *
     * @param collection   来源集合.
     * @param propertyName 要提取的属性名.
     */
    public static <T> List<T> extractList(final Collection<?> collection, final String propertyName) {
        if (CollectionUtils.isEmpty(collection)) {
            return Lists.newArrayList();
        }
        List<T> list = new ArrayList<T>(collection.size());
        try {
            for (Object obj : collection) {
                T property = (T) PropertyUtils.getProperty(obj, propertyName);
                // 判断为空
                if (property != null) {
                    if (property instanceof String) {
                        String p = ((String) property);
                        p = p.trim();
                        // " "是blank,但是不是empty
                        if (StringUtils.isBlank(p)) {
                            continue;
                        }
                    }
                    // 去重
                    if (!list.contains(property)) {
                        list.add(property);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

   

    public static void main(String[] args) {
    
        User user = new User("name");
        User user2 = new User("name2");
		List<User> userList = Arrays.asList(user,user2);
        List<Integer> nameList= JavaKit.extractList(userList, "name");
        System.out.println(nameList);
    }
}
public class User {
	private String name;
	
	public User(String name) {
		this.name= name;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

}