I have a custom object like the following one.
public class Count {
private int words;
private int characters;
//getters & setters && all args constructor
void Count decrease(Count other) {
this.words -= other.words;
this.characters -= other.characters;
return this;
}
}
I want to achieve the next result, eg:
Count book1 = new Count(10, 35);
Count book2 = new Count(6, 10);
the result would be: Count result = Count(4, 25) -> ([10-6], [35-10])
I tried this solution but it didn't work.
Stream.of(book1, book2).reduce(new CountData(), CountData::decrease)
It's possible to achieve this result using reduce operation or another stream operation from java >=8?
The following ad hoc solution uses a single-element stream of book2
to be subtracted from a seed initialized with book1
values:
Count reduced = Stream.of(book2)
.reduce(new Count(book1.getWords(), book1.getCharacters()), Count::decrease);
Here value of book1
is not affected.
However, for this specific case this can be done without Stream API:
Count reduced = new Count(book1.getWords(), book1.getCharacters())
.decrease(book2);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.