Map 遍历
map对象使用stream来进行操作。
map.entrySet().stream().map(Map.Entry::getValue)
stream引用
Box one = new Box();
one.setId(1);
one.setName("one");
Box two = new Box();
two.setId(2);
two.setName("two");
Box thr = new Box();
thr.setId(3);
thr.setName("thr");
List<Box> boxList = Lists.newArrayList();
boxList.add(one);
boxList.add(two);
boxList.add(thr);
int id = 2;
List<Box> filterBoxList = boxList.stream().filter(b->b.getId()==id).collect(Collectors.toList());
two.setId(3);
System.out.println(FastJsonUtil.toJSONString(filterBoxList));
list转string,每一个用逗号隔开
idSet.stream().map(g->String.valueOf(g)).collect(Collectors.joining(","))
list去重
这里的去重是简单的去重,主要针对字符串、基本类型等,如果是自定义的对象,可能效果没有那么好,要改写hashcode()方法等。
List<Long> idList = Lists.newArrayList();
idList.add(1l);
idList.add(2l);
idList.add(3l);
idList.add(3l);
idList.add(3l);
idList.add(3l);
idList.add(3l);
idList = idList.stream().distinct().collect(Collectors.toList());
list 自定义对象类 字段去重
如果自己定义了一个对象,想对这个对象里的集合元素进行去重,按照某个字段来去重,这就有点复杂了,这样操作就可以了。
import static java.util.Comparator.comparingLong;
import static java.util.stream.Collectors.collectingAndThen;
import static java.util.stream.Collectors.toCollection;
// 根据id去重
List<Person> unique = appleList.stream().collect(
collectingAndThen(
toCollection(() -> new TreeSet<>(comparingLong(Apple::getId))), ArrayList::new)
);
求集合中min、sum、max等值
通过reduce方法来实现,举个例子如下:
Stream<String> stream = Stream.of("I", "love", "you", "too");
Optional<String> longest = stream.reduce((s1, s2) -> s1.length()>=s2.length() ? s1 : s2);
通过reduce方法来得到最小长度的字符串,你也可以更改里面的代码来实现其他逻辑。