Java: Remove duplicate options from collection using Iterator

 

 

Combined with the Iterator to remove duplicate options in the collection, this approach has the disadvantage that the final result is not necessarily ordered.

public class test {

	public static void main(String[] args) {

// create a collection
		ArrayList list = new ArrayList<>();
// add content to the collection
		list.add(1);
		list.add(2);
		list.add(3);
		list.add(3);
		list.add(2);
		list.add(3);
		list.add(4);
		list.add(4);
		list.add(4);

// call the method to remove duplicates
		checkRepeat(list);

// output the contents of the collection after removing duplicates
		System.out.println(list);

	}

	public static void checkRepeat(ArrayList list) {
		Iterator it = list.iterator();

		while (it.hasNext()) {
// define a counter
			int count = 0;

			Integer str = (Integer) it.next();

// Take out a content in the iterator and loop through the content in the list
			for (int i = 0; i < list.size(); i++) {
// If there are the same, the counter count is incremented by 1
				if (list.get(i) == str) {
					count++;
				}
			}
// If the value of the counter is greater than or equal to 2, it means that there are duplicates, and the current content in the iterator is deleted
			if (count >= 2) {
				it.remove();
			}
			count = 0;
		}

	}

}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325329619&siteId=291194637