forEach clause to iterate through indexes of a Vector

Steve Waters :

I have a method like this:

public void addVector(Vector myVector) {
    if (myVector == null) {
        return;
    }

    Collection<String> values = new ArrayList<>();

    for (int i = 0; i < myVector.size(); i++) {
        values.add(((String[]) myVector.get(i))[1]);
    }

    this.addItems(values);
}

For the life of me I can't figure out how to make a forEach clause from that. Is it possible to itereate through the indexes [i] in a forEach loop?

Eran :

You don't need the index if you use the enhanced for loop:

for (Object obj : myVector) {
    values.add(((String[]) obj)[1]);
}

Of course it would be better to use a parameterized type (Vector<String[]>) and avoid the casting.

Or if you meant the actual forEach method:

myVector.forEach(o -> values.add(((String[]) o)[1]));

or, even better, use Stream with collect instead of forEach:

List<String> values = 
    myVector.stream()
            .map(o -> (String[]) o)[1])
            .collect(Collectors.toList());

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=84783&siteId=1