一、数组转List
1、Arrays.asList()
List<String> list= new ArrayList<>(Arrays.asList(array));
2、Collections.addAll()
List<String> list = new ArrayList<>(array.length);
Collections.addAll(list,array);
3、List.of()
Java9
新增方法,定义在List
接口内,并且为静态方法,故可以由类名直接调用
List<String> list = List.of(array);
二、List 去重方法总结
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("kelly");
list.add("yzz");
list.add("hhh");
list.add("kelly");
list.add("yzz");
System.out.println("list"+list);
//方法一:使用java8新特性stream进行List去重
List newList = (List) list.stream().distinct().collect(Collectors.toList());
System.out.println("java8新特性stream去重:"+ newList);
//方法二:set集合判断去重,不打乱顺序
Set set =new HashSet<>();
List newList1 = new ArrayList();
for(String str : list){
if(set.add(str)){
newList1.add(str);
}
}
System.out.println("list"+list);
System.out.println("set集合判断去重:"+newList1);
//方法三 :遍历后判断赋给另一个list集合
List newList2 = new ArrayList();
for (String str : list) {
if(!newList2.contains(str)){
newList2.add(str);
}
}
System.out.println("list"+list);
System.out.println("赋值新list去重:"+newList2);
// 方法四:set和list转换去重
Set set2 = new HashSet();
List newList3 = new ArrayList();
set2.addAll(list);
newList3.addAll(set2);
System.out.println("list"+list);
System.out.println("set和list转换去重:" + newList3);
}
打印结果
list[kelly, yzz, hhh, kelly, yzz]
java8新特性stream去重:[kelly, yzz, hhh]
list[kelly, yzz, hhh, kelly, yzz]
set集合判断去重:[kelly, yzz, hhh]
list[kelly, yzz, hhh, kelly, yzz]
赋值新list去重:[kelly, yzz, hhh]
list[kelly, yzz, hhh, kelly, yzz]
set和list转换去重:[yzz, hhh, kelly]
三、List 过滤排序分页
public static void main(String[] args) {
Integer page =1;
Integer size = 10;
User user1 = new User("kelly","12345",2);
User user2 = new User("yzz","26489",1);
User user3 = new User("meet","25369",1);
User user4 = new User("yu","120368",2);
User user5 = new User(null,"120368",null);
List<User> list = new ArrayList<User>();
list.add(user1);
list.add(user2);
list.add(user3);
list.add(user4);
list.add(user5);
System.out.println("list"+list);
List list1= list.stream().filter(user-> user.getUsername()==null).collect(Collectors.toList());
System.out.println("用Stream类过滤username为空的元素");
System.out.println(list1);
List list2= list.stream().filter(user-> user.getUsername()!=null)
.sorted(Comparator.comparing(User::getUsername))
.collect(Collectors.toList());
System.out.println("对username不为空的元素按照username进行排序");
System.out.println(list2);
//然后把两个结果集合并
List<User> listAll = new ArrayList<User>();
listAll.addAll(list1);
listAll.addAll(list2);
List<User> collect = listAll.stream().skip((page - 1) * size).limit(size).collect(Collectors.toList());
System.out.println("通过skip()和limit组合来分页");
System.out.println(collect);
}