#3 Java进阶系列--集合元素的查询与删除

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/yzh18373476791/article/details/82353660

在上一章中,我们对集合的排序进行了系统的讲解,这一节我们来谈一谈集合的查询与删除。当然我们仍然以下面的实体基础类作为基础:
Entity<T>.java

package com.yzh.maven.base.entity;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class Entity<T> implements Comparable<T>{
    @Override
    public int compareTo(T t) {
        return 0;
    }
    public List<T> sortList(List<T> list){
        Collections.sort(list,new Comparator<T>(){
            @SuppressWarnings("unchecked")
            @Override
            public int compare(T t1,T t2) {
                return ((Comparable<T>) t1).compareTo(t2);
            }
        });
        return list;
    }
}

②Student.java

package com.yzh.maven.entity;
import com.yzh.maven.base.entity.Entity;
public class Student extends Entity<Student>{
    private Integer stuId;
    private String name;
    private String password;
    private String sex;
    private int age;
    public Integer getStuId() {
        return stuId;
    }
    public void setStuId(Integer stuId) {
        this.stuId = stuId;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public String getSex() {
        return sex;
    }
    public void setSex(String sex) {
        this.sex = sex;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }

     @Override
    public String toString() {
        return "Student [stuId=" + stuId + ", name=" + name + ", password="
                + password + ", sex=" + sex + ", age=" + age + "]";
    }

    @Override
    public int compareTo(Student stu) {
        if(this == stu){
            return 0;            
        }else{   
            if(stuId.compareTo(stu.getStuId()) > 0){
                return 1;
            }else if(stuId.compareTo(stu.getStuId()) > 0){
                return 0;
            }else{
                return -1;
            }
        }
    }
}

③UserInfo.java

package com.yzh.maven.entity;
import org.springframework.data.mongodb.core.mapping.Document;
import com.yzh.maven.base.entity.Entity;
@Document(collection="userInfo")
public class UserInfo extends Entity<UserInfo>{
    private String userName;
    private String password;
    private int age;
    private String sex;
    private String tel;
    private String email;
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public String getSex() {
        return sex;
    }
    public void setSex(String sex) {
        this.sex = sex;
    }
    public String getTel() {
        return tel;
    }
    public void setTel(String tel) {
        this.tel = tel;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public UserInfo(String userName, String password, int age, String sex,
            String tel, String email) {
        super();
        this.userName = userName;
        this.password = password;
        this.age = age;
        this.sex = sex;
        this.tel = tel;
        this.email = email;
    }
    public UserInfo() {
        super();
    }

    @Override
    public int compareTo(UserInfo u) {
        if(this == u){
            return 0;            
        }else{   
            if(userName.compareTo(u.getUserName()) > 0){
                return 1;
            }else if(userName.compareTo(u.getUserName()) == 0){
                return 0;
            }else{
                return -1;
            }
        }
    }

    @Override
    public String toString() {
        return "UserInfo [userName=" + userName + ", password=" + password
                + ", age=" + age + ", sex=" + sex + ", tel=" + tel + ", email="
                + email + "]";
    }
}

一、集合元素的查询
1、编写基础实体类方法(只支持多条件单值查询)

/**
 * @function name searchList
 * @Description 多条件查询list
 * @param list
 * @param params
 * @return
 * @date 2018-09-03
 * @author yzh
 */ 
public List<T> searchList(List<T> list,Map<String,Object> params){
    List<T> newList = new ArrayList<T>(); 
    for(T t:list){
        //判断是否一致的标识
        boolean flag = false;
        Iterator<Entry<String, Object>> it = params.entrySet().iterator();
        //遍历map
        while(it.hasNext()){
            String key = it.next().getKey();
            String value = params.get(key)+"";
            if(value.equals(getFiledValue(key,t))){
                flag = true;
            //如果不一致,终止此次循环,确保所有查询条件一致才一致
            }else{
                flag = false;
                break;
            }
        }
        //如果符合查询条件,那么就加入list中
        if(flag){
            if(!newList.contains(t)){
                newList.add(t);
            }
        }
    }
    return newList;
}


/**
 * @function name getFiledValue
 * @Description 获取List对象元素的某个属性的值
 * @param filedName 字段名
 * @param <T>
 * @return
 * @date 2018-08-07
 * @author yzh
 */ 
public static <T> String getFiledValue(String filedName,T t){
    Field field = null;
    Object fieldVal = null;
    try {
        field = t.getClass().getDeclaredField(filedName);
        //设置私有属性允许访问,否则无法将值set进实体类的私有属性中
        field.setAccessible(true);
        fieldVal = field.get(t);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return fieldVal+"";
}

2、测试

Map<String,Object> userMap = new HashMap<String,Object>();
userMap.put("userName","LinDa");
userMap.put("age","23");
List<UserInfo> userList = user1.searchList(list1,userMap);
System.out.println(userList);

Map<String,Object> stuMap = new HashMap<String,Object>();
stuMap.put("name","B");
List<Student> stuList = stu1.searchList(list2,stuMap);
System.out.println(stuList);
/**
output:
[UserInfo [userName=LinDa, password=123456, age=23, sex=男, tel=12345678, email=123@qq.com]]
[Student [stuId=11, name=B, password=124, sex=女, age=21]]
*/

二、集合元素的删除
我们知道,集合元素的删除可以使用remove()方法,例如:
1、

List<String> list3 = new ArrayList<String>();
list3.add("A");
list3.add("B");
list3.add("C");
System.out.println(list3);
//通过下标删除
list3.remove(0);
System.out.println(list3);
//通过元素来删除
list3.remove("B");
System.out.println(list3);
/**output:
[A, B, C]
[B, C]
[C]
*/

如果删除的元素是对象呢?而且需要根据某一个字段来删除List的对象元素?应该如何处理呢?代码如下所示。

2、

/**
 * @function name removeListCaseByFieldName
 * @Description 根据实体类的某个字段和输入值来删除元素
 * @param filed 字段名
 * @param removeByValue 删除值
 * @param List<T>
 * @return
 * @date 2018-09-03
 * @author yzh
 */ 
public  List<T> removeListCaseByFieldName(List<T> list,String field,String removeByValue){
    for(int i = 0;i<list.size();i++){
        T t = list.get(i);
        if(getFiledValue(field,t).equals(removeByValue)){
            list.remove(t);
        }
    }
    return list;
}

3、测试:

user1.removeListCaseByFieldName(list1,"userName","Jake");
System.out.println("删除后:");
for(UserInfo u:list1){
    System.out.println(u);
}
/**output:
UserInfo [userName=LinDa, password=123456, age=23, sex=男, tel=12345678, email=123@qq.com]
UserInfo [userName=yzh, password=123458, age=24, sex=男, tel=12345670, email=1235@qq.com]
*/

4、当然还有一些稍微复杂一点的需求:通过指定某一个list元素来删除另一个list的元素,代码如下所示。

/**
 * @function name removeOtherListCaseByTheListCaseName
 * @Description 根据list的某个属性名称删除另一个list的某个元素
 * @param
 * @return
 * @date 2018-09-03
 * @author yzh
 * @param <T>
**/
public static <T> List<T> removeOtherListCaseByTheListCaseName(List<T> list1,List<T> list2,String fileName) {
    int []arr = new int[list2.size()]; 
    int [] newArr = new int[arr.length];
    //记录重复元素下标
    int b = 0;
    for(int i = 0;i<list1.size();i++){
        for(int m = 0;m<list2.size();m++){
            T t1 = list1.get(i);
            String filedVal1 = getFiledValue(fileName,t1);
            T t2 = list2.get(m);
            //根据fileName属性获取t1的fileName属性值
            String filedVal2 = getFiledValue(fileName,t2);
            try {
                if(filedVal1.equals(filedVal2)){
                    //做删除操作时,遍历的长度一定要是list.size(),因为后面移除对象之后就会导致list长度动态变化,如果使用常量表示,会导致边界异常
                    //记录重复元素的位置
                    arr[b] = i;
                    b++;
                }else{
                    continue;
                }
            } catch (Exception e) {
                e.printStackTrace();
            } 
        }
    }
    //因为要删除list里面的多个的值,所以会涉及到一个问题,就是当你删除掉下标为1的元素时,
    //原来下标为2的元素会自动改变自己的下标为0,后面的元素依次把自己的下标值减1
    //鉴于这种情况,我们想循环删除list中的多个元素的话,就必须从后往前删,这样保障了你删除了一个元素之后,
    //list中元素的下标移动不会影响到那些需要删除,但是还未删除到的元素 
    //1.顺序排序
    Arrays.sort(arr);
    //2.反向数组
    for(int i = 0;i<arr.length;i++){
        newArr[i] = arr[arr.length-i-1];
    }
    //3.删除元素
    for(int i = 0;i<newArr.length;i++){
        list1.remove(newArr[i]);
    }
    return list1;
  }
展开阅读全文

没有更多推荐了,返回首页