ArrayList去除集合中字符串的重复值

/*
* 需求:ArrayList去除集合中字符串的重复值
*
* 分析:
* 1.创建一个集合对象
* 2.添加多个字符串元素
* 3.创建一个新的集合
* 4.拿旧集合中的元素到新集合中去找
* A:有则 不要
* B:没有则添加到新集合中
* 5.遍历输出 新集合
*/

package com.ma.arraylist;

import java.util.ArrayList;
import java.util.Iterator;

/**
 * ArrayList去除集合中字符串的重复值
 * @author ma
 *
 */
public class ArrayListDemo {

	/*
	 * 需求:ArrayList去除集合中字符串的重复值 
	 * 
	 * 分析:
	 * 		1.创建一个集合对象
	 * 		2.添加多个字符串元素
	 * 		3.创建一个新的集合
	 * 		4.拿旧集合中的元素到新集合中去找
	 * 			A:有则 不要
	 * 			B:没有则添加到新集合中
	 * 		5.遍历输出 新集合
	 */
	
	public static void main(String[] args) {
		//1.创建一个ArrayList集合对象
		ArrayList arrList = new ArrayList();
		
		//向ArrayList添加字符串元素
		arrList.add("hello");
		arrList.add("world");
		arrList.add("hello");
		arrList.add("java");
		arrList.add("你好");
		arrList.add("世界");
		arrList.add("你好");
		arrList.add("爪哇");
		
		//3.创建一个新的集合
		ArrayList arrList1 = new ArrayList();
		
		/*
		 *4.拿旧集合中的元素到新集合中去找
		 * 		A:有则 不要
		 * 		B:没有则添加到新集合中
		 */
		//得到迭代器
		Iterator it = arrList.iterator();
		
		//遍历集合arrList
		while (it.hasNext()) {
			String str = (String) it.next();
			
			//如arrlist1中不包含str,则把str添加支arrList1中
			if(!arrList1.contains(str)){
				arrList1.add(str);
			}
			
		}
		
		//5.遍历输出 新集合
		//得到迭代器
		Iterator it1 = arrList1.iterator();
		
		//遍历输出 新集合
		while (it1.hasNext()) {
			String str1 = (String) it1.next();
			System.out.println(str1);
		}
		
		
	}
}

  输出结果:

    hello
    world
    java
    你好
    世界
    爪哇

转载于:https://www.cnblogs.com/majingang/p/9018734.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值