Skip to content

Instantly share code, notes, and snippets.

@edylle
Last active July 5, 2023 07:35
Show Gist options
  • Save edylle/b05a5e72e1b2522218bbf956de1a0df3 to your computer and use it in GitHub Desktop.
Save edylle/b05a5e72e1b2522218bbf956de1a0df3 to your computer and use it in GitHub Desktop.
Java 8 lambda stream filter example - sum of BigDecimal
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
class StreamFilter {
public static void main(String[] args) {
List<Wrapper> list = new ArrayList<>();
list.add(new Wrapper("true"));
list.add(new Wrapper("false"));
list.add(new Wrapper("true"));
BigDecimal total = list
.stream()
.filter(w -> "true".equals(w.getFilter())) // optional
.map(Wrapper::getValue)
.reduce(BigDecimal.ZERO, BigDecimal::add);
System.out.println(total); // it will print 20
}
}
class Wrapper {
BigDecimal value;
String filter;
Wrapper(String filter) {
value = BigDecimal.TEN; // mocked value
this.filter = filter;
}
public BigDecimal getValue() {
return value;
}
public String getFilter() {
return filter;
}
}
@user20161119
Copy link

Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment