Java | 集合&Stream使用示例

欢迎参观我的博客,一个Vue 与 SpringBoot结合的产物:https://poetize.cn

原文链接:https://poetize.cn/article?id=50

HashMap的compute()方法

如果 key 对应的 value 不存在,则返回该 null,如果存在,则返回通过 remappingFunction 重新计算后的值。

Map<String, List<JSONObject>> map = new HashMap<>();
map.compute(jsonObject.getString("name"), (k, v) -> {
    if (v == null) {
        v = new ArrayList<>();
    }
    v.add(jsonObject);
    return v;
});

Collectors.toMap

//List转Map
List<Map<String, String>> resultList = new ArrayList<>();
resultList.stream().collect(Collectors.toMap(data -> data.get("key"), Function.identity()));

//Map排序
Map<String, Long> map = new HashMap<>();
map.entrySet().stream().sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
    .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (x, y) -> {
        throw new AssertionError();
    }, LinkedHashMap::new));

//Map计算
Map<String, Long> map = new HashMap<>();
map.entrySet().stream().collect(Collectors.toMap(data -> data.getKey(), Map.Entry::getValue, Long::sum));

//List转Map重复Key处理
Collectors.toMap(data -> data.getString("id"), data -> {
        Set<String> s = new HashSet<>();
        s.add(checkData(data));
        return s;
    }, (k1, k2) -> {
        k1.addAll(k2);
        return k1;
    })

Collectors.joining

stream().collect(Collectors.joining("`,`", "`", "`"));

Stream分页

List<Person> persons = ...;
List<Person> page = persons.stream().skip((pageQuery.getPageNo() - 1) * pageQuery.getPageSize()).limit(pageQuery.getPageSize()).collect(Collectors.toList());

Stream.peek()

对流中的每个元素执行一个操作,而不改变流的内容。

List<String> result = new ArrayList<>();
data.stream().peek(d -> result.add(d)).filter();

Stream排序

//倒叙
List<Teacher> value = ...;
List<Teacher> sortList = value.stream().sorted(Comparator.comparing(Teacher::getName, (a, b) -> {
    if (a == null) a = "";
    if (b == null) b = "";
    return b.compareTo(a);
}).thenComparing(Teacher::getUpdateTime, (a, b) -> {
    if (a == null) a = new Date(0L);
    if (b == null) b = new Date(0L);
    return b.compareTo(a);
})).collect(Collectors.toList());

Collectors.groupingBy

Map<String, List<Teacher>> groupMap = list.stream().collect(Collectors.groupingBy(Teacher::getName, LinkedHashMap::new, Collectors.toList()));

Map<String, Map<String, List<Teacher>>> groupMap = list.stream().collect(Collectors.groupingBy(Teacher::getName, LinkedHashMap::new, Collectors.groupingBy(Teacher::getAge, Collectors.toList())));

Map<String, Set<String>> groupMap = list.stream().collect(Collectors.groupingBy(Teacher::getName, Collectors.mapping(Teacher::getAge, Collectors.toSet())));
posted @ 2023-09-27 10:35  LittleDonkey  阅读(31)  评论(0编辑  收藏  举报