public class ListTest {
public static void main(String[] args) {
//*****************1.模糊查询**********************
List<User> userList = new ArrayList<>();
for (int i = 0; i < 11; i++) {
User user = new User();
user.setId(i);
user.setName("张三" + i+"A");
userList.add(user);
}
for (User user : userList) {
System.out.print(user.getName() + "\t");
}
//模糊查询 查询后的数据封装到一个新的newUserList里
List<User> newUserList = new ArrayList<>();
for (int i = 0; i < userList.size(); i++) {
if (userList.get(i).getName().indexOf("9") > -1) {
newUserList.add(userList.get(i));
}
}
for (User user2 : newUserList) {
System.out.println("\n"+"模糊查询后的数据:"+user2.getName() + "\t");
}
//*****************2.分页查询**********************
int page =1;
int rows =10;
int size = userList.size();
int pageCount=size/rows;
int fromIndex = rows * (page - 1);
int toIndex = fromIndex + rows;
if (toIndex >= size) {
toIndex = size;
}
if(page>=pageCount+1){
fromIndex=0;
toIndex=0;
}
userList.subList(fromIndex, toIndex).stream().forEach(user -> {
System.out.print(user.getName() + "\t");
});
//*****************3.List模糊搜索不区分大小写法**********************
Pattern pattern = Pattern.compile("a", Pattern.CASE_INSENSITIVE);
for (User user :userList){
Matcher matcher = pattern.matcher(user.getName());
// matches是精确查询,如果要模糊匹配,matcher.find()即可以进行模糊匹配
if (matcher.matches()) {
System.out.print(user.getName()+"\t");
}
}
//*****************4.List取出一组对象的某个属性组成一个新集合**********************
List<Integer> ids=userList.stream().map(User::getId).collect(Collectors.toList());
for(int i=0;i<ids.size();i++){
System.out.print(ids.get(i)+"\t");
}
System.out.print("*****************升序********************");
Collections.sort(ids);
for(int i=0;i<ids.size();i++){
System.out.print(ids.get(i)+"\t");
}
System.out.print("*****************降序********************");
Collections.reverse(ids);
for(int i=0;i<ids.size();i++){
System.out.print(ids.get(i)+"\t");
}
//************根据单个字段字段去除重复*******************
List<User> userLists = userList.stream() .collect(
Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(user -> user.getName()))), ArrayList::new));
//************根据多个字段去除重复*******************
List<User> userList3 = userList.stream() .collect(
Collectors.collectingAndThen(
Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(user -> user.getName()+";"+user.getId()))), ArrayList::new));
//************List去重两个相同的实体类对象或者相同的单个对象字段**************
List<String> classNameList = new ArrayList(new HashSet(userList));
//************根据某个字段分组**************
userList.stream().collect(Collectors.groupingBy(User::getName));
}
}
list常见的模糊查询 分页 排序 取出单一元素集合 去重等处理
最新推荐文章于 2022-08-29 20:25:29 发布