Collector classを生成する
toList() streamの各要素としたListをreturnするCollectorを生成
toSet() streamの各要素としたSetをreturnするCollectorを生成
toMap() streamの各要素をFunctionで加工したkey, mapをMapとしてreturnするCollectorを生成
class Value {
int price;
String name;
public Value(int price, String name) {
this.price = price;
this.name = name;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String toString() {
return "price:" + price + " name:" + name;
}
}
public class Outer {
public static void main(String[] args) {
List<Value> l = Arrays.asList(
new Value(1,"andy"),
new Value(2,"john"),
new Value(3,"laula"),
new Value(4,"miki"),
new Value(5,"sally"));
Stream<Value> st = l.stream();
List<Value> l2 = st.collect(Collectors.toList());
l2.forEach(System.out::println);
System.out.println("----------------------------");
st = l.stream();
Set<Value> s = st.collect(Collectors.toSet());
s.forEach(System.out::println);
System.out.println("----------------------------");
st = l.stream();
Map<String, Value> mp = st.collect(Collectors.toMap(
Value::getName,
b -> b));
mp.keySet().stream().forEach(System.out::println);
mp.keySet().stream().forEach(a -> System.out.println(mp.get(a)));
}
}
price:1 name:andy
price:2 name:john
price:3 name:laula
price:4 name:miki
price:5 name:sally
----------------------------
price:3 name:laula
price:1 name:andy
price:2 name:john
price:4 name:miki
price:5 name:sally
----------------------------
miki
sally
john
laula
andy
price:4 name:miki
price:5 name:sally
price:2 name:john
price:3 name:laula
price:1 name:andy