集册 Java实例教程 合并列表并删除重复项

合并列表并删除重复项

欢马劈雪     最近更新时间:2020-01-02 10:19:05

503
合并列表并删除重复项


//package com.nowjava;

import java.util.ArrayList;

import java.util.Iterator;// from 时代Java公众号 - N o w J a  v a . c o m

import java.util.List;


public class Main {

    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;

        /*
        n o w j a   v  a . c o m - 时  代  Java 提 供
        */

        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
展开阅读全文