Last active
July 5, 2023 07:35
-
-
Save edylle/b05a5e72e1b2522218bbf956de1a0df3 to your computer and use it in GitHub Desktop.
Java 8 lambda stream filter example - sum of BigDecimal
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks