For Each over a getList()? [duplicate] - java

This question already has answers here:
How does the Java 'for each' loop work?
(29 answers)
Closed 9 years ago.
for ( SomeListElement element : objectWithList.getList() ) { ... }
What is the above snippet translated to?
What I am mostly interested in is if the getList() method called once, or with each iteration/element?

Its equivalent to
for(Iterator<SomeListElement> i = objectWithList.getList().iterator();
i.hasNext(); ) {
SomeListElement element = i.next();
//access element here
}

It gets translated to below code snippet, and objectWithList.getList() is called only once.
for (Iterator i = objectWithList.getList().iterator(); i.hasNext();) {
SomeListElement e = (SomeListElement) i.next();
}

Related

HashMap iterating and deleting element [duplicate]

This question already has answers here:
Why is a ConcurrentModificationException thrown and how to debug it
(8 answers)
Closed 4 years ago.
public void execute(HashMap<String,Coordonnee >c)
{
c.forEach((k,v) -> {
p = m.getMin(c);
sky.add(p);
c.remove(p.getNom());
});
}
This throws a java.util.ConcurrentModificationException.
How can I fix that ?
Use removeIf function:
map.entrySet().removeIf
Use iterator:
Iterator<Object> it = map.keySet().iterator();
while (it.hasNext())
{
it.next();
if (something)
it.remove();
}
you cannot delete an element of the list while looping through it. You should use Iterator for that.
public void execute(HashMap<String,Coordonnee >c)
{
Iterator cItr = c.iterator();
while(cItr.hasNext())
{
c = cItr.next();
p = m.getMin(c);
sky.add(p);
cItr.remove(p.getNom());
}
}

Removing a set from it self while iterating [duplicate]

This question already has answers here:
How to avoid "ConcurrentModificationException" while removing elements from `ArrayList` while iterating it? [duplicate]
(10 answers)
Closed 5 years ago.
I've been stuck on this for awhile now. I am trying to remove elements of a set if they make a set criteria. However when iterating when I try to remove the element it fails.
I get the java.util.ConcurrentModificationException
private static void smallerSet(Set<Map<String, Int>> set){
for (Map<String, Integer> map : set){
for (String String : map.keySet()){
if ( true){
set.remove(map);
}
else{
//System.out.println("test");
}
}
}
}
Any advice would be greatly appreciated.
You cannot remove elements from a Collection while iterating over it with the enhanced for loop.
You should use an explicit Iterator and remove with the Iterator's remove() method:
Iterator<Map<String, Integer>> iter = set.iterator();
while (iter.hasNext ()) {
Map<String, Integer> map = iter.next();
for (String str : map.keySet()){
if (some condition) {
iter.remove();
break; // you should probably break from the inner loop
// after removing an element
} else {
//System.out.println("test");
}
}
}

Cannot remove hashset in java [duplicate]

This question already has answers here:
Why is a ConcurrentModificationException thrown and how to debug it
(8 answers)
Closed 8 years ago.
i got a problem with hashset, I cannot remove a hashset, and here is the code
//take stopword list from file
public void stopWordList(){
openFile("D:/ThesisWork/Perlengkapan/stopword.txt");
while(x.hasNext()){
String a = x.nextLine();
a = a.toLowerCase();
stopWords.add(a);
}
}
//the method to remove stopword
public void stopWordRemoval(){
stopWordList();
//if the word in the streams set is equal to stopword, it should be removed
for(String word:streams){
for(String sw:stopWords){
if(word.equals(sw)){
streams.remove(word);
}
}
}
But, it gives me an exception, it says like :
Exception in thread "main" java.util.ConcurentModificationException, could anyone help me? thanks :)
This is because the foreach loop (for (Whatever x: something)) internally creates an Iterator.
And when you remove from the Iterable (the something above) being iterated, a well-behaved Iterator will detect that "hey, you have modified my babies beyond my knowledge" and throw this exception.
What you should do is this:
final Iterator<String> iterator = stream.iterator();
String word;
while (iterator.hasNext()) {
word = iterator.next();
if (stopWords.contains(word))
iterator.remove(); // This is safe: an iterator knows how to remove from itself
}
you are performing a concurrent modification - you are iterating over a collection and modifiying it not by the iterator, you should transform your code to this:
for (Iterator<String> it = streams.iterator(); it.hasNext();) {
String word = it.next();
for (String sw : stopWords) {
if (word.equals(sw)) {
it.remove();
break;
}
}
}

Search for String in List [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
public Account findByInterest(String interest){
for(Map.Entry<Long, Account> e : accounts.entrySet()){
for(int i = 0; i < e.getValue().getInterests().size(); i++)
{
if(e.getValue().getInterests().get(i) == interest){
return e.getValue();
}
}
}
return null;
}
I'm trying to search in a HashTable of Objects to find an objected with a List of Strings, which has the same string as this method receives... What am I doing wrong?
To compare string values use the equals method.
Change
if(e.getValue().getInterests().get(i) == interest){
to
if(e.getValue().getInterests().get(i).equals(interest)){

java+ ConcurrentModificationException forEach(enhanced) loop single thread [duplicate]

This question already has answers here:
Iterating through a Collection, avoiding ConcurrentModificationException when removing objects in a loop
(31 answers)
ConcurrentModificationException for ArrayList [duplicate]
(6 answers)
Closed 9 years ago.
I am not able to understand the reason, why the below code is throwing CME, even when this is run as single thread application
import java.util.ArrayList;
import java.util.List;
public class ConcurrentModification {
public static void main(String[] args) {
ConcurrentModification con = new ConcurrentModification();
con.call();
}
void call() {
List<Integer> l = new ArrayList<Integer>();
for (int i = 0; i <= 10000; i++) {
l.add(i);
}
for (Integer j : l) {
if (j % 3 == 0) {
l.remove(j);
}
}
}
}
Reason:(after going through the answer and other links)
You are not permitted to mutate a list while you are iterating over it.
Only Iterator remove's method can be used to delete element from list
For Each loop is using iterator beneath it
but l.remove(j) is not using that iterator, which causes the exception
You are not permitted to mutate a list while you are iterating over it. Your l.remove(j) causes the list l to change, but you're inside a for (Integer j : l) loop.
For this you need to use iterator
for (Iterator<ProfileModel> it = params[0].iterator(); it
.hasNext();) {
ProfileModel model = it.next();
DBModel.addProfile(homeScreenActivity, model, profileId);
}
I used it to add data in database..Hope it helps

Categories