1

I would like to find the most efficent way how to find 1st element of collection which is inside another collection where I take also the 1st entry. I think this is "ugly" solution.

public class UnitLine {}


public class Unit {

private Collection<UnitLine> unitLines;

public Collection<UnitLine> getUnitLines() {
    return unitLines;
}

}

public class Wrapper {

Collection<Unit> units;

public Collection<Unit> getUnits() {
    return units;
}

}

public static void main(String[] args) {

    Wrapper wrapper = new Wrapper();

    Unit unit = wrapper.getUnits().stream().findFirst().orElseGet(null);
    if (unit != null) {
        UnitLine unitLine = unit.getUnitLines().stream().findFirst().orElseGet(null);
        if (unitLine != null) {
            // do something
        }
    }
}
vviston
  • 183
  • 1
  • 12
  • Does this answer your question? [Best way to get value from Collection by index](https://stackoverflow.com/questions/1047957/best-way-to-get-value-from-collection-by-index) – Kris Oct 21 '21 at 12:52
  • Hmm not really - I would like to know how to get first unitLine of the first unit in most efficient way because that is what I need to do with these two collections. – vviston Oct 21 '21 at 12:57
  • Why dont you think of using a TreeMap instead of list of lists ? And index the map with running numbers ? – Kris Oct 21 '21 at 13:07
  • I am not able to change the "input collections" they are defined as Collections so I need to work with that. – vviston Oct 21 '21 at 13:20

1 Answers1

4

Turning Optionals into nulls means you can't take advantage of the nice features of Optional. Here's an equivalent of your code that uses Optional map and orElse usefully:

UnitLine unitLine = wrapper.getUnits().stream()
  .findFirst()
  .map(Unit::getLines)
  .orElse(Collections.emptySet()).stream()
  .findFirst()
  .orElse(null);

That code gets the first element of the first collection, or null if the first collection is empty. To get the first element of the first non-empty collection, you can use flatMap:

wrapper.getUnits().stream()
  .map(Unit::getUnitLines)
  .flatMap(Collection::stream)
  .findFirst()
MikeFHay
  • 8,562
  • 4
  • 31
  • 52