一、java集合判空
1、判断list是否实例化:list!=null
2、判断list包含的元素个数:list.isEmpty()(建议使用这种方式)和list.size()==0是等价的
判断集合不为空:
if(list!=null&&!list.isEmpty())
{
}
else
{
}
3、使用CollectionUtils工具类:CollectionUtils.isNotEmpty(Collection col)
判断集合为空:
if(CollectionUtils.isEmpty(list))//(list==null||list.isEmpty())
{
}
else
{
}
二、list转map
Student:year(Integer)、month(Integer)、age(Double)
(1)
Map<Integer,Student> collect=stuList.stream().collect(Collectors.toMap(Student::getYear,student->student));
(2)
Map<Integer,List<Student>> map=studentList.stream().collect(Collectors.groupingBy(Student::getYear));
(3)
Map<Integer,Double> tradeAmountMap=stuList.stream().collect(Collectors.goupingBy(p->p.getYear(),Collectors.summingDouble(p->p.age)));(分组并根据分组字段求和)
三、map转list
Map<String,String> userObjHashMap=new HashMap();
userObjHashMap.put(“user1”,”hello”);
userObjHashMap.put(“user2”,”world”);
List<String> resultList=userObjHashMap.values.stream().collect(Collectors.toList());
四、list转list
List<BigDecimal> newList=stringList.stream().map(p->{return “”.equals(p)?null:new BigDecimal(p)}).collect(Collectors.toList());
五、取出list中对象某个属性值,拼接成字符串并以,隔开
//创建list对象
UserObj userObj = new UserObj(1,"20",55);
UserObj userObj2 = new UserObj(5,"20",66);
UserObj userObj3 = new UserObj(10,"20",30);
//创建集合
List<UserObj> userList = new ArrayList<>();
userList.add(userObj);
userList.add(userObj2);
userList.add(userObj3);
String testUserStr= userList.stream().map(UserObj::getTid).map(String::valueOf).collect(Collectors.joining(","));