最近接触了一些stream的东西,顺便写了一些例子,保存下来,代码如下:
static class Town{
int area = 0;
String name;
public int getArea() {
return area;
}
public void setArea(int area) {
this.area = area;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public static void main(String[] args) {
List<Town> townList = new ArrayList<>();
for (int i = 0;i<10;i++){
Town temp = new Town();
temp.setArea(2);
townList.add(temp);
}
//求和
long areaSum = townList.stream().mapToInt(i->{
//这里可以写一些业务处理逻辑
i.getArea();
return i.getArea();
}).sum();
System.out.println(areaSum);
//另一种写法
long areaSum1 = townList.stream().mapToInt(Town::getArea).sum();
System.out.println(areaSum1);
System.out.println(Stream.of("hello", "world", "ww", "java").
collect(Collectors.toMap(o->{
//可以写自己的业务逻辑
o.toString();
return o.toLowerCase();
},o->o.toUpperCase())));
//简单写法
System.out.println(Stream.of("hello", "world", "ww", "java").
collect(Collectors.toMap(String::toLowerCase,String::toUpperCase)));
//分组
Map<Integer,List<Town>> map = townList.stream().
collect(Collectors.groupingBy(t->t.getArea()));
System.out.println(map);
}
今天又遇到了一个复杂类型集合去重和字符串拼接,先记下来:
//查询优惠券关联的活动
List<Map<String,Object>> actions = dal_mkt_cou_type.getListAutoType("getActByCoupon",info);
String infomation = actions.stream()
.filter(distinctByKey(i->i.get("action_id")))
.map(p -> {
StringBuffer str = new StringBuffer();
str.append(p.get("action_id"))
.append(",")
.append(p.get("action_name"));
return str.toString();
}).collect(Collectors.joining(";", "【", "】"));
public <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
Set<Object> seen = ConcurrentHashMap.newKeySet();
return t -> seen.add(keyExtractor.apply(t));
}