Java 怎么合并 List 并删除重复项

2019年5月30日19:05:11 评论 83

1.简介

Java 怎么合并 List 并删除重复项?——请看下文。

2.代码

/**
 * 版权所有 编程十万个怎么办(www.tah1986.com)
 */
public class MergeListsAndRemoveDuplicates {
	public static List<Integer> mergeListsAndRemoveDuplicates(
			List<Integer> listOne, List<Integer> listTwo) {

		if (listOne.isEmpty()) {
			return listTwo;
		}
		if (listTwo.isEmpty()) {
			return listOne;
		}

		Iterator<Integer> listTwoIterator = listTwo.iterator();
		int nextTwo = listTwoIterator.next();
		List<Integer> result = new ArrayList<Integer>();
		boolean twoNotEmpty = true;

		for (int nextOne : listOne) {

			while (nextOne > nextTwo && twoNotEmpty) {
				result.add(nextTwo);
				if (listTwoIterator.hasNext()) {
					nextTwo = listTwoIterator.next();
				} else {
					twoNotEmpty = false;
					nextTwo = 0;
				}
			}

			if (nextOne == nextTwo) {
				if (listTwoIterator.hasNext()) {
					nextTwo = listTwoIterator.next();
				} else {
					twoNotEmpty = false;
					nextTwo = 0;
				}
			}

			result.add(nextOne);
		}

		if (twoNotEmpty) {
			result.add(nextTwo);
		}
		while (listTwoIterator.hasNext()) {
			result.add(listTwoIterator.next());
		}

		return result;
	}
}

3.总结

示例代码演示了 Java 怎么合并 List 并删除重复项,具体步骤参见示例代码。

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: