java中list集合移除元素

  • 2021年10月29日
  • Java

package com.longlonggo.demo;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import com.longlonggo.entity.Product;

/**
 * <p>
 * Description: list集合移除元素
 * </p>
 * <p>
 * Created on 2017年6月15日
 * </p>
 * <p>
 * Copyright: Copyright (c) 2017-2018
 * </p>
 * 
 * @author 石马人山 me@longlonggo.com
 */
public class MyTest {
	public static void main(String[] args) {
		Product productEntity; // 对象声明
		int size = 5; // 产生随机对象个数
		// 产生随机对象集合List<Product> productList = new ArrayList<>();
		for (int i = 0; i < size; i++) {
			productEntity = new Product();
			productEntity.setProductId(new Random().nextInt(10) + 1);
			productList.add(productEntity);
		}
		print(productList);
		// 移除id=2的list对象
		// 方法一)【官方推荐】使用迭代器移除,注意该处的it.remove()是迭代器的方法,不是list的remove方法Iterator<Product>
		// it = productList.iterator();
		while (it.hasNext()) {
			Product _p = it.next();
			if (_p.getProductId() == 2) {
				it.remove();
			}
		}
		print(productList);
		// 方法二)常规for循环删除
		// 注意在移除元素后,必须将循环索引减1,因为数组发生改变,迭代的索引也需要跟着减小
		for (int i = 0; i < productList.size(); i++) {
			if (productList.get(i).getProductId() % 2 == 0) {
				productList.remove(i);
				i--;// 必须进行索引减1
			}
		}
		print(productList);
		// 方法三)增强型for循环删除
		// 将要删除的元素添加到一个新的集合中,然后通过removeAll()函数删除的元素集合
		List<Product> rmList = new ArrayList<>();
		for (Product _p : productList) {
			if (_p.getProductId() % 2 == 0) {
				rmList.add(_p);
			}
		}
		productList.removeAll(rmList);
		print(productList);
	}

	/**
	 * 打印函数
	 * 
	 * @param productList
	 */
	public static void print(List<Product> productList) {
		System.out.println("n-----------------------------------");
		for (int i = 0; i < productList.size(); i++) {
			System.out.print(productList.get(i).getProductId() + " ");
		}
	}
}

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注