Java, using Iterator to find ArrayList and remove matching objects

Basically, the user sends the string that the Iterator looks for in an ArrayList. When found, the Iterator will delete the object containing the string.

Since each of these objects contains two lines, I find the problem of writing these lines as one.

Friend current = it.next(); String currently = current.getFriendCaption(); 

Thanks for any help!

+6
source share
1 answer

You do not need them in one line, just use remove to remove the element when it matches:

 Iterator<Friend> it = list.iterator(); while (it.hasNext()) { if (it.next().getFriendCaption().equals(targetCaption)) { it.remove(); // If you know it unique, you could `break;` here } } 

Full demo:

 import java.util.*; public class ListExample { public static final void main(String[] args) { List<Friend> list = new ArrayList<Friend>(5); String targetCaption = "match"; list.add(new Friend("match")); list.add(new Friend("non-match")); list.add(new Friend("match")); list.add(new Friend("non-match")); list.add(new Friend("match")); System.out.println("Before:"); for (Friend f : list) { System.out.println(f.getFriendCaption()); } Iterator<Friend> it = list.iterator(); while (it.hasNext()) { if (it.next().getFriendCaption().equals(targetCaption)) { it.remove(); // If you know it unique, you could `break;` here } } System.out.println(); System.out.println("After:"); for (Friend f : list) { System.out.println(f.getFriendCaption()); } System.exit(0); } private static class Friend { private String friendCaption; public Friend(String fc) { this.friendCaption = fc; } public String getFriendCaption() { return this.friendCaption; } } } 

Conclusion:

  $ java ListExample 
 Before:
 match
 non-match
 match
 non-match
 match

 After:
 non-match
 non-match 
+35
source

Source: https://habr.com/ru/post/901756/


All Articles