1

I'm trying to convert Java loop code to Java 8 stream. I have an ArrayList of Row objects that should sum all deliveredLength excluding the Row objects that has the same content as another Row object that has the same content.

Java Loops

public int getDeliveredLength() {
    List<Row> distinct = new ArrayList<>();
    for (Row row : rows) {
        if (sameContent(distinct, row)) {
            continue;
        }
        distinct.add(row);
    }
    int sum = 0;
    for (Row row : distinct) {
        sum += row.getDeliveredLength();
    }
    return sum;
}

private boolean sameContent(List<Row> list, Row other) {
    for (Row row : list) {
        if (other.sameContent(row)) {
            return true;
        }
    }
    return false;
}

What would the Java 8 stream code be?

public int getDeliveredLength() {
  return rows.stream().filter(??).map(??).mapToInt(Row::getDeliveredLength).sum()
}
Tagir Valeev
  • 97,161
  • 19
  • 222
  • 334
Fireblaze
  • 242
  • 3
  • 5

1 Answers1

4

Why do you write a new method sameContent, and do you not override the equals method? Using equals has the advantage that many classes and methods from the standard library call it to compare instances of your class.

Given that you use equals, you can use the standard Stream.distinct() method, which returns a stream of distinct values. So your Java 8 stream expression becomes:

rows.stream().distinct().mapToInt(Row::getDeliveredLength).sum()
Hoopje
  • 12,677
  • 8
  • 34
  • 50
  • `Row ` might be defined not only by its content. For example its index – gontard Nov 23 '15 at 15:53
  • Row contains start, end and comment and content, so equals and hashcode need to include all fields. sameContent() only check the content-field – Fireblaze Nov 23 '15 at 15:54
  • 2
    Or `Row` is from an external library. It is possible to wrap it into a custom object having the proper equals / hashCode though, like in [this answer](http://stackoverflow.com/a/23699499/1743880) – Tunaki Nov 23 '15 at 15:55