开发中对于stream有一些小的用法。进行总结一下。
将一个数组切分为多个小数组
/**
* Description: Java8 Stream分割list集合
* @param list 集合数据
* @param splitSize 几个分割一组
* @return 集合分割后的集合
*/
public static <T> List<List<T>> splitList(List<T> list, int splitSize) {
//判断集合是否为空
if (CollectionUtils.isEmpty(list)) {
return Collections.emptyList();
}
//计算分割后的大小
int maxSize = (list.size() + splitSize - 1) / splitSize;
//开始分割
return Stream.iterate(0, n -> n + 1)
.limit(maxSize)
.parallel()
.map(a -> list.parallelStream().skip(a * splitSize).limit(splitSize).collect(Collectors.toList()))
.collect(Collectors.toList());
}
将学生按分数进行分组,并返回各分数的学生名称
@Data
@AllArgsConstructor
class Study {
public String name;
public Integer scope;
}
List<Study> list = new ArrayList<Study>() {{
add(new Study("张三", 10));
add(new Study("李四", 10));
add(new Study("王五", 20));
add(new Study("赵六", 20));
add(new Study("田七",20));
}};
Map<Integer, List<String>> collect = list.stream()
.collect(
Collectors.groupingBy(
Study::getScope,
Collectors.mapping(
Study::getName,
Collectors.toList()
)
)
);
System.out.println(collect);
按指定字段进行去重
下列学生中,赵六,分数为20的重复录入了一次,通过treeset进行去重操作
@Data
@AllArgsConstructor
class Study {
public String name;
public Integer scope;
}
List<Study> list = new ArrayList<Study>() {{
add(new Study("张三", 10));
add(new Study("李四", 10));
add(new Study("王五", 20));
add(new Study("赵六", 20));
add(new Study("赵六", 20));
add(new Study("田七",20));
}};
List<Study> collect = list.stream()
.distinct()
.collect(
Collectors.collectingAndThen(
Collectors.toCollection(
() -> new TreeSet<>(Comparator.comparing(o -> o.getName() + o.getScope()))
),
ArrayList::new
)
);
System.out.println(collect);
多字段排序
@Data
@AllArgsConstructor
@NoArgsConstructor
class demoEnt{
public Integer age;
public Integer index;
}
List<demoEnt> list = new ArrayList<>();
list.add(new demoEnt(11, 2));
list.add(new demoEnt(11,3));
list.add(new demoEnt(12,1));
//按年龄倒序并按index正序
List<demoEnt> collect = list.stream().sorted(
Comparator.comparing(demoEnt::getAge)
.reversed()
.thenComparing(demoEnt::getIndex)
).collect(Collectors.toList());
System.out.println(collect);