码迷,mamicode.com
首页 > 编程语言 > 详细

一行代码实现java list去重

时间:2014-10-09 02:14:48      阅读:199      评论:0      收藏:0      [点我收藏+]

标签:java   list   去重   


1.不带类型写法:
List listWithoutDup = new ArrayList(new HashSet(listWithDup));
2.带类型写法(以String类型为例):
1)Java 7以下写法:
List<String> listWithoutDup = new ArrayList<String>(new HashSet<String>(listWithDup));
2)Java 7及以上写法:
List<String> listWithoutDup = new ArrayList<>(new HashSet<>(listWithDup));

样例:
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

public class Test {
	public static void main(String[] args) {
		List<String> listWithDup = new ArrayList<String>();
		listWithDup.add("1");
		listWithDup.add("2");
		listWithDup.add("3");
		listWithDup.add("1");

		List<String> listWithoutDup = new ArrayList<String>(new HashSet<String>(listWithDup));
		System.out.println("list with dup:"+ listWithDup);
		System.out.println("list without dup:"+ listWithoutDup);
	}
}
样例运行结果:
list with dup:[1, 2, 3, 1]
list without dup:[3, 2, 1]

一行代码实现java list去重

标签:java   list   去重   

原文地址:http://blog.csdn.net/u014569459/article/details/39899567

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!