44 lines
953 B
Java
Raw Normal View History

2015-12-02 09:20:27 -08:00
// streams/Reduce.java
// (c)2021 MindView LLC: see Copyright.txt
2015-12-02 09:20:27 -08:00
// We make no guarantees that this code is fit for any purpose.
2016-09-23 13:23:35 -06:00
// Visit http://OnJava8.com for more book information.
2015-12-02 09:20:27 -08:00
import java.util.*;
import java.util.stream.*;
class Frobnitz {
int size;
Frobnitz(int sz) { size = sz; }
@Override public String toString() {
2015-12-02 09:20:27 -08:00
return "Frobnitz(" + size + ")";
}
// Generator:
static Random rand = new Random(47);
static final int BOUND = 100;
2015-12-02 09:20:27 -08:00
static Frobnitz supply() {
return new Frobnitz(rand.nextInt(BOUND));
2015-12-02 09:20:27 -08:00
}
}
public class Reduce {
public static void main(String[] args) {
Stream.generate(Frobnitz::supply)
.limit(10)
.peek(System.out::println)
.reduce((fr0, fr1) -> fr0.size < 50 ? fr0 : fr1)
.ifPresent(System.out::println);
}
}
/* Output:
Frobnitz(58)
Frobnitz(55)
Frobnitz(93)
Frobnitz(61)
Frobnitz(61)
Frobnitz(29)
Frobnitz(68)
Frobnitz(0)
Frobnitz(22)
Frobnitz(7)
Frobnitz(29)
*/