How to cut Java for each loop in half?
I work a lot for each loop in Java. I use them to make each class of my objects do "drawing", but it takes a lot of memory, so I want to cut it in half, is there a way to make the list not complete for each loop?
for(Tile tile: tiles){
tile.draw();
}
I want to:
for(Tile tile: (half of)tiles){
tile.draw();
}
Is this possible, or do I just need to get the length of the plates and when it reaches the number, break the loop?
source to share
Since you figured out what you have ArrayList
, you can use the function subList
to get an idea of ββthe first half of the list
for(Tile tile: tiles.subList(0, tiles.size()/2){
tile.draw();
}
It uses a loop foreach
and pretty concise and readable code.
Since the sub-list is just a view over the original list, there is no penalty for copying to the new list.
source to share
Well, there's always old style for
. Assuming which tiles
is an instance List<Tile>
:
for(int i = 0; i < tiles.size() / 2; i++)
{
tiles.get(i).draw();
}
Or, if you want to preserve the order of the iterator:
Iterator<Tile> iter = tiles.iterator();
int i = 0;
int halfway = tiles.size() / 2;
while(i < halfway)
{
Tile tile = iter.next();
tile.draw();
i++;
}
source to share
I want to render only half of the list of "tiles" and, if necessary, the other half.
If it doesn't matter which order you make the halves in, you can do it like this:
int counter = 0;
for(Tile tile: tiles) {
if (counter++ % 2 == 0) {
tile.draw();
}
}
Do counter++ %2 == 1
for the other half.
source to share
Oooh, there are several ways to do this.
JAVA
final List<Tile> tiles = .... // create the list of Tile instances
//Be sure that tiles is not empty before to do that
final List<Tile> firstHalfSubList=tiles.subList(0, tiles.size()/2);
final List<Tile> secondHalfSubList=tiles.subList(tiles.size()/2, tiles.length());
Note that the two half lists support tiles, so make them immutable.
But my favorite is using the Guava library
guava
import com.google.common.collect.Lists;
import com.google.common.math.IntMath;
import java.math.RoundingMode;
final List<Tile> tiles = .... // create the list of Tile instances
final int partitionSize = IntMath.divide(tile.size(), 2, RoundingMode.UP);
final List<List<Tile>> partitions = Lists.partition(tile, partitionSize);
and you have a list of two sections and you can iterate over them!
source to share
The answers given here already seem fine to me, but I noticed in your question that you want to have a for-each loop. So you can use a stream to cut the list in half:
List<Tile> halve =tiles.stream().limit(tiles.size()/2).collect(Collectors.toList());
for(Tile tile : halve)
{
}
This is the same approach as other answers, just the point of style selection
source to share