Search code examples
javaandroidarraylistcollectionsjava-stream

Java find biggest size of list in list


I want to find the biggest size() of List<TileFrame> tileFrames that is inside of List<TileAnimation> class.

TileAnimation.java

public class TileAnimation {
private long localGID;
private List<TileFrame> tileFrames;

public long getLocalGID() {
    return localGID;
}

public void setLocalGID(long localGID) {
    this.localGID = localGID;
}

public List<TileFrame> getTileFrames() {
    return tileFrames;
}

public void setTileFrames(List<TileFrame> tileFrames) {
    this.tileFrames = tileFrames;
}

public TileAnimation(long localGID, List<TileFrame> tileFrames) {
    this.localGID = localGID;
    this.tileFrames = tileFrames;
}

@Override
public String toString() {
    return "TileAnimation{" +
            "localGID=" + localGID +
            ", tileFrames=" + tileFrames +
            '}';
}
}

TileFrame.java

public class TileFrame {
private long tileId;
private long duration;

public long getTileId() {
    return tileId;
}

public void setTileId(long tileId) {
    this.tileId = tileId;
}

public long getDuration() {
    return duration;
}

public void setDuration(long duration) {
    this.duration = duration;
}

public TileFrame(long tileId, long duration) {
    this.tileId = tileId;
    this.duration = duration;
}

@Override
public String toString() {
    return "TileFrame{" +
            "tileId=" + tileId +
            ", duration=" + duration +
            '}';
    }
}

Let's say I have such list of objects and I filled it later on:

private List<TileAnimation> tileAnimations = new ArrayList<>();

then how to find such max size in inner List<TileFrame> of List<TileAnimations> ? All the solutions I know when there are just one list with sigular fields without inner lists, but here it is something new for me and I could not find any solution in the internet of such issue.


Solution

  • you can achieve it simply by using streams

    int maxTileFramesSize = tileAnimations.stream()
           .mapToInt(tileAnimation -> tileAnimation.getTileFrames().size())
           .max()
           .orElse(0);