OnJava8-Examples/collectiontopics/StreamFillMaps.java

49 lines
1.5 KiB
Java
Raw Normal View History

2016-12-30 22:22:39 -08:00
// collectiontopics/StreamFillMaps.java
2016-12-30 17:23:13 -08:00
// (c)2017 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.*;
class Letters implements Supplier<Pair<Integer,String>> {
private int number = 1;
private char letter = 'A';
@Override
public Pair<Integer,String> get() {
return new Pair<>(number++, "" + letter++);
}
}
public class StreamFillMaps {
public static void main(String[] args) {
Map<Integer,String> m =
Stream.generate(new Letters())
.limit(11)
.collect(Collectors.toMap(Pair::key, Pair::value));
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)
.collect(Collectors.toMap(Pair::key, Pair::value));
System.out.println(mcs);
// A key Supplier and a single value:
Map<Character,String> mcs2 = Stream.generate(
() -> Pair.make(cc.get(), "Val"))
.limit(8)
.collect(Collectors.toMap(Pair::key, Pair::value));
System.out.println(mcs2);
}
}
/* Output:
{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}
*/