dorcsi
dorcsi

Reputation: 325

Array to Map through for loop

I know its a very trivial issue, but I still need some help. I have an array and I want to get its element into a map.

 public static Map<String, String> getSomeId() {

    Map<String, String> map = new HashMap<>();
    File folder = new File("src/main/resources/someData");
    File[] listOfFiles = folder.listFiles();
    for (int i = 0; i < listOfFiles.length; i++) {
        if (listOfFiles[i].isFile()) {
            map.put("someId", listOfFiles[i].getName().substring(0, 13));
        }
    }
    return map;
}

I know that the content of the map gets overwritten in every loop and my map will contains only the last element put into. How can I get all element of the array into my map?

Thank you!

Upvotes: 0

Views: 83

Answers (1)

Qingfei Yuan
Qingfei Yuan

Reputation: 1212

what about this?

map.put("someId" + i, listOfFiles[i].getName().substring(0, 13));

Upvotes: 3

Related Questions