Pankaj Pathania Pankaj Pathania - 6 months ago 26
Java Question

No such element in map, why?

I am working on a code in which if I try arrays everything works fine but when i try to solve that example with list it displays

Exception in thread "main" java.util.NoSuchElementException
at java.util.AbstractList$Itr.next(Unknown Source)
at com.delete.files.DeleatingFiles.check(DeleatingFiles.java:27)
at com.delete.files.DeleatingFiles.main(DeleatingFiles.java:60)


and the code is :

Map<String, String> map = new HashMap<String, String>();
File folder = new File("F://fileIO/");
if (folder.isDirectory()) {
List<File> filesName = Arrays.asList(folder.listFiles());
Iterator<File> itList = filesName.listIterator();
while (itList.hasNext()) {
map.put(itList.next().getName(), itList.next().toString());
}
System.out.println(map);
}
} else {
System.err.println("something is wrong");
}
}


EDIT 1: All I am trying is to save file name with absolute path as key value pair.
EDIT 2: can't use as
String
next=itrList.next() as Iterator is of File type.

Now , can anyone tell me the cause of problem ??
Please tell me if there is something wrong.

Thanks.

Answer

In your code map.put(itList.next().getName(), itList.next().toString()); call next() twice even you check itList.hasNext() once.

while (itList.hasNext()) { // Check once
   map.put(itList.next().getName(), itList.next().toString()); // next() Call twice here
}

Your code may have to be corrected as like follows

Map<String, String> map = new HashMap<String, String>();
    File folder = new File("F://fileIO/");
    if (folder.isDirectory()) {
        List<File> filesName = Arrays.asList(folder.listFiles());
        Iterator<File> itList = filesName.listIterator();
        File file;
        while (itList.hasNext()) {
            file = itList.next();
            map.put(file.getName(), file.toString());
        }
        System.out.println(map);
    } 
    else {
        System.err.println("something is wrong");
    }
Comments