您好,登錄后才能下訂單哦!
Java中怎么使用Iterator迭代器刪除集合重復(fù)選項(xiàng),相信很多沒(méi)有經(jīng)驗(yàn)的人對(duì)此束手無(wú)策,為此本文總結(jié)了問(wèn)題出現(xiàn)的原因和解決方法,通過(guò)這篇文章希望你能解決這個(gè)問(wèn)題。
結(jié)合迭代器Iterator刪除集合中重復(fù)的選項(xiàng),這種方法有一個(gè)缺點(diǎn)就是最終的結(jié)果不一定是有序的。
public class test { public static void main(String[] args) {// 創(chuàng)建一個(gè)集合 ArrayList list = new ArrayList<>();// 往集合中添加內(nèi)容 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);// 調(diào)用刪除重復(fù)項(xiàng)的方法 checkRepeat(list);// 輸出刪除重復(fù)項(xiàng)后的集合內(nèi)容 System.out.println(list); } public static void checkRepeat(ArrayList list) { Iterator it = list.iterator(); while (it.hasNext()) {// 定義一個(gè)計(jì)數(shù)器 int count = 0; Integer str = (Integer) it.next();// 取出迭代器中的一個(gè)內(nèi)容,循環(huán)一遍list中的內(nèi)容 for (int i = 0; i < list.size(); i++) {// 如果有相同的,計(jì)數(shù)器count就加1 if (list.get(i) == str) { count++; } }// 如果計(jì)數(shù)器的值大于等于2就說(shuō)明有重復(fù)的,就刪除迭代器中當(dāng)前的內(nèi)容 if (count >= 2) { it.remove(); } count = 0; } }}
看完上述內(nèi)容,你們掌握J(rèn)ava中怎么使用Iterator迭代器刪除集合重復(fù)選項(xiàng)的方法了嗎?如果還想學(xué)到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。