2015-11-11 20:20:04 -08:00
|
|
|
// streams/MapCollector.java
|
2015-12-15 11:47:04 -08:00
|
|
|
// (c)2016 MindView LLC: see Copyright.txt
|
2015-11-15 15:51:35 -08:00
|
|
|
// We make no guarantees that this code is fit for any purpose.
|
|
|
|
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
|
2015-11-11 20:20:04 -08:00
|
|
|
import java.util.*;
|
|
|
|
import java.util.stream.*;
|
|
|
|
|
|
|
|
class Pair {
|
|
|
|
public final Character c;
|
|
|
|
public final Integer i;
|
|
|
|
public Pair(Character c, Integer i) {
|
|
|
|
this.c = c;
|
|
|
|
this.i = i;
|
|
|
|
}
|
|
|
|
public Character getC() { return c; }
|
|
|
|
public Integer getI() { return i; }
|
|
|
|
@Override
|
|
|
|
public String toString() {
|
|
|
|
return "Pair(" + c + ", " + i + ")";
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
class RandomPair {
|
|
|
|
Random rand = new Random(47);
|
|
|
|
// An infinite iterator of random capital letters:
|
2015-11-14 16:18:05 -08:00
|
|
|
Iterator<Character> capChars = rand.ints(65,91)
|
2015-11-11 20:20:04 -08:00
|
|
|
.mapToObj(i -> (char)i)
|
|
|
|
.iterator();
|
|
|
|
public Stream<Pair> stream() {
|
|
|
|
return rand.ints(100, 1000).distinct()
|
|
|
|
.mapToObj(i -> new Pair(capChars.next(), i));
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
public class MapCollector {
|
|
|
|
public static void main(String[] args) {
|
|
|
|
Map<Integer, Character> map =
|
|
|
|
new RandomPair().stream()
|
|
|
|
.limit(8)
|
|
|
|
.collect(
|
|
|
|
Collectors.toMap(Pair::getI, Pair::getC));
|
|
|
|
System.out.println(map);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
/* Output:
|
2015-11-14 16:18:05 -08:00
|
|
|
{688=W, 309=C, 293=B, 761=N, 858=N, 668=G, 622=F, 751=N}
|
2015-11-11 20:20:04 -08:00
|
|
|
*/
|