一行代码去除List中的重复数据

1. 核心代码:

List<String> listWithoutDup = new ArrayList<String>(new HashSet<String>(list));

2. 测试代码(junit4)

@Test
public void removeDuplicateDatas() {

	StringBuilder buf = new StringBuilder(100);

	buf.append("安铝变ALV,八河变,高坡换流站,高坡换流站,贵阳站,贵阳站,纳雍二厂,纳雍一厂,");
	buf.append("青岩站,青岩站,夏云变XIY,幺铺变YIP");

	String endSts = buf.toString();

	// 将数据添加到List中
	List<String> list = Arrays.asList(endSts.split(","));

	// 去除List中的重复数据
	List<String> listWithoutDup = new ArrayList<String>(
			new HashSet<String>(list));

	System.out.println(listWithoutDup);
}

3. 执行结果

[安铝变ALV, 青岩站, 纳雍二厂, 纳雍一厂, 八河变, 高坡换流站, 夏云变XIY, 幺铺变YIP, 贵阳站]

如果不需要返回 List,而是返回 String,可参考 http://xurichusheng.iteye.com/blog/1055338

猜你喜欢

转载自xurichusheng.iteye.com/blog/2261038