**
Stream
**
1.JSON转Map
String data = "{\"A\":\"0000\",\"B\":\"1111\"}";
Map<String, String> itemData = JSON.parseObject(data, new TypeReference<Map<String, String>>(){});
2.filter和map
filter:用于通过设置的条件过滤出元素
map:用于映射每个元素到对应的结果
只获取flag为true的id
List<Long> ids= goodsList.stream().filter(p -> p.getFlag().equals(true)).map(Goods::getId).collect(Collectors.toList());
3.forEach
遍历list,通过XXX获取
list.forEach(XXX-> {
Goods goods = goodsDao.findById(XXX.getId());
voList.add(new GoodsVO(XXX,));
});
4.limit
获取限定的流
只获取一个goods
list.stream().limit(1).forEach(goods->{
voList.add(goods);
});
5.sorted
用于对流进行排序
//对常用类型的数值进行排序
Random random = new Random();
random.ints().limit(10).sorted().forEach(System.out::println);
/
list.stream().map(p->p.getGoodsId()).sorted().forEach(System.out::println);
根据对象的主键(goodsId)进行排序
(Comparator本人理解为实现接口)
//递增
list.stream().sorted(Comparator.comparing(Goods::getGoodsId)).forEach(goods->{
System.out.println(goods.getGoodsName());
});
//逆向(递减)
list2.stream().sorted(Comparator.comparing(Goods::getGoodsId).reversed()).forEach(goods->{
System.out.println(goods.getGoodsName());
});
//其他
grouping.entrySet().stream()
.sorted((o1,o2) -> {
Integer k1 = getWeight(o1.getKey());
Integer k2 = getWeight(o2.getKey());
return k1.compareTo(k2);
})
.forEachOrdered(x -> result.put(x.getKey(), x.getValue()));
6.List和数组 互转
//List转数组
String[] arrays = list.toArray(new String[0]);
//或
String[] arrays = list.stream().toArray(String[]::new);
//数组转List
List<String> stringList = Arrays.asList(array);
//或者
List<String> list = Stream.of(arrays).collect(Collectors.toList());
7.Set和数组 互转
//Set转数组
String[] array=set.toArray(new String[0]);
//或
String[] array= set.stream().toArray(String[]::new);
//数组转Set
Set<String> set = new HashSet<>(Arrays.asList(array));
//或
Set<String> set = Stream.of(array).collect(Collectors.toSet());
8.Set和List互转
//Set转List
List<String> list=new ArrayList<>(set);
或
List list=Stream.of(set.toArray(new String[0])).collect(Collectors.toList());
//List转Set
Set<String> set=new HashSet<>(list);
//或
Set<String> set = list.stream().collect(Collectors.toSet());
9.Map和Set互转
Set<Long> Ids = goodsMap.keySet();
10.List转Map
Map<Long, 对象> sheetBoMap = sheetBoList.stream().collect(Collectors.toMap(对象::getId, Function.identity(), (k1, k2)->k2)));
//(k1, k2)->k2) 若出现Id重复的,则替换为第2个对象;少了这一句也可以,但是会抛出异常
其他
将List 转为 id01,id02,id03
//import org.apache.commons.lang3.StringUtils;
String ids= StringUtils.join(idList, ",");