2016-12-30 22:22:39 -08:00
|
|
|
// collectiontopics/StreamFillMaps.java
|
2021-01-31 15:42:31 -07:00
|
|
|
// (c)2021 MindView LLC: see Copyright.txt
|
2016-07-05 14:46:09 -06: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.
|
2016-07-05 14:46:09 -06:00
|
|
|
import java.util.*;
|
|
|
|
import java.util.function.*;
|
|
|
|
import java.util.stream.*;
|
|
|
|
import onjava.*;
|
|
|
|
|
2017-01-22 16:48:11 -08:00
|
|
|
class Letters
|
|
|
|
implements Supplier<Pair<Integer,String>> {
|
2016-07-05 14:46:09 -06:00
|
|
|
private int number = 1;
|
|
|
|
private char letter = 'A';
|
2021-01-31 15:42:31 -07:00
|
|
|
@Override public Pair<Integer,String> get() {
|
2016-07-05 14:46:09 -06:00
|
|
|
return new Pair<>(number++, "" + letter++);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
public class StreamFillMaps {
|
|
|
|
public static void main(String[] args) {
|
|
|
|
Map<Integer,String> m =
|
|
|
|
Stream.generate(new Letters())
|
|
|
|
.limit(11)
|
2017-01-22 16:48:11 -08:00
|
|
|
.collect(Collectors
|
|
|
|
.toMap(Pair::key, Pair::value));
|
2016-07-05 14:46:09 -06:00
|
|
|
System.out.println(m);
|
|
|
|
|
|
|
|
// Two separate Suppliers:
|
|
|
|
Rand.String rs = new Rand.String(3);
|
|
|
|
Count.Character cc = new Count.Character();
|
|
|
|
Map<Character,String> mcs = Stream.generate(
|
|
|
|
() -> Pair.make(cc.get(), rs.get()))
|
|
|
|
.limit(8)
|
2017-01-22 16:48:11 -08:00
|
|
|
.collect(Collectors
|
|
|
|
.toMap(Pair::key, Pair::value));
|
2016-07-05 14:46:09 -06:00
|
|
|
System.out.println(mcs);
|
|
|
|
|
|
|
|
// A key Supplier and a single value:
|
|
|
|
Map<Character,String> mcs2 = Stream.generate(
|
|
|
|
() -> Pair.make(cc.get(), "Val"))
|
|
|
|
.limit(8)
|
2017-01-22 16:48:11 -08:00
|
|
|
.collect(Collectors
|
|
|
|
.toMap(Pair::key, Pair::value));
|
2016-07-05 14:46:09 -06:00
|
|
|
System.out.println(mcs2);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
/* Output:
|
2017-05-10 11:45:39 -06:00
|
|
|
{1=A, 2=B, 3=C, 4=D, 5=E, 6=F, 7=G, 8=H, 9=I, 10=J,
|
|
|
|
11=K}
|
|
|
|
{b=btp, c=enp, d=ccu, e=xsz, f=gvg, g=mei, h=nne,
|
|
|
|
i=elo}
|
|
|
|
{p=Val, q=Val, j=Val, k=Val, l=Val, m=Val, n=Val,
|
|
|
|
o=Val}
|
2016-07-05 14:46:09 -06:00
|
|
|
*/
|