当前位置: 代码网 > it编程>编程语言>Java > Java中Stream API处理Map初始化的操作方法

Java中Stream API处理Map初始化的操作方法

2025年10月10日 Java 我要评论
当然可以! stream api 提供了多种方式来实现 map 的构建、存在则更新、不存在则添加的操作。以下是几种常用的方法:1. 使用collectors.tomap()处理重复键import ja

当然可以! stream api 提供了多种方式来实现 map 的构建、存在则更新、不存在则添加的操作。以下是几种常用的方法:

1. 使用collectors.tomap()处理重复键

import java.util.*;
import java.util.stream.collectors;
public class streammapoperations {
    public static void main(string[] args) {
        list<person> people = arrays.aslist(
            new person("alice", 25),
            new person("bob", 30),
            new person("alice", 28), // 重复的key
            new person("charlie", 35)
        );
        // 方法1: 使用tomap的合并函数来处理重复键
        map<string, integer> personmap = people.stream()
            .collect(collectors.tomap(
                person::getname,      // key映射器
                person::getage,       // value映射器
                (existing, newvalue) -> newvalue // 合并函数:新值覆盖旧值
            ));
        system.out.println("覆盖策略: " + personmap);
        // 输出: {alice=28, bob=30, charlie=35}
    }
}
class person {
    private string name;
    private int age;
    public person(string name, int age) {
        this.name = name;
        this.age = age;
    }
    public string getname() { return name; }
    public int getage() { return age; }
}

2. 不同的合并策略

// 合并函数的不同实现策略
map<string, integer> map1 = people.stream()
    .collect(collectors.tomap(
        person::getname,
        person::getage,
        (oldvalue, newvalue) -> oldvalue // 保留旧值
    ));
map<string, integer> map2 = people.stream()
    .collect(collectors.tomap(
        person::getname,
        person::getage,
        (oldvalue, newvalue) -> oldvalue + newvalue // 求和
    ));
map<string, list<integer>> map3 = people.stream()
    .collect(collectors.tomap(
        person::getname,
        person -> new arraylist<>(arrays.aslist(person.getage())),
        (oldlist, newlist) -> {
            oldlist.addall(newlist);
            return oldlist;
        }
    ));
system.out.println("保留旧值: " + map1); // {alice=25, bob=30, charlie=35}
system.out.println("求和: " + map2);     // {alice=53, bob=30, charlie=35}
system.out.println("收集所有值: " + map3); // {alice=[25, 28], bob=[30], charlie=[35]}

3. 复杂的对象操作

class product {
    private string category;
    private string name;
    private double price;
    private int quantity;
    public product(string category, string name, double price, int quantity) {
        this.category = category;
        this.name = name;
        this.price = price;
        this.quantity = quantity;
    }
    // getters
    public string getcategory() { return category; }
    public string getname() { return name; }
    public double getprice() { return price; }
    public int getquantity() { return quantity; }
}
public class complexmapoperations {
    public static void main(string[] args) {
        list<product> products = arrays.aslist(
            new product("electronics", "laptop", 1000, 2),
            new product("electronics", "phone", 500, 5),
            new product("books", "novel", 20, 10),
            new product("electronics", "laptop", 900, 3) // 重复商品,价格不同
        );
        // 按商品名称分组,计算总价值(价格*数量)
        map<string, double> productvaluemap = products.stream()
            .collect(collectors.tomap(
                product::getname,
                product -> product.getprice() * product.getquantity(),
                double::sum // 存在则累加
            ));
        system.out.println("商品总价值: " + productvaluemap);
        // 输出: {laptop=4700.0, phone=2500.0, novel=200.0}
    }
}

4. 分组收集器的高级用法

// 按类别分组,并收集每个类别的商品列表
map<string, list<product>> productsbycategory = products.stream()
    .collect(collectors.groupingby(product::getcategory));
// 按类别分组,并计算每个类别的总价值
map<string, double> categorytotalvalue = products.stream()
    .collect(collectors.groupingby(
        product::getcategory,
        collectors.summingdouble(p -> p.getprice() * p.getquantity())
    ));
// 按类别分组,并获取每个类别最贵的商品
map<string, optional<product>> mostexpensivebycategory = products.stream()
    .collect(collectors.groupingby(
        product::getcategory,
        collectors.maxby(comparator.comparingdouble(product::getprice))
    ));
system.out.println("按类别分组: " + productsbycategory.keyset());
system.out.println("类别总价值: " + categorytotalvalue);

5. 自定义map操作(更复杂的逻辑)

// 如果存在则更新,不存在则添加的复杂逻辑
map<string, productstats> productstatsmap = products.stream()
    .collect(collectors.tomap(
        product::getname,
        product -> new productstats(1, product.getprice() * product.getquantity(), product.getprice()),
        (existingstats, newstats) -> {
            // 存在则更新:数量累加,总价值累加,价格取平均值
            int totalcount = existingstats.getcount() + newstats.getcount();
            double totalvalue = existingstats.gettotalvalue() + newstats.gettotalvalue();
            double avgprice = totalvalue / (existingstats.getcount() + newstats.getcount());
            return new productstats(totalcount, totalvalue, avgprice);
        }
    ));
class productstats {
    private int count;
    private double totalvalue;
    private double averageprice;
    public productstats(int count, double totalvalue, double averageprice) {
        this.count = count;
        this.totalvalue = totalvalue;
        this.averageprice = averageprice;
    }
    // getters and tostring
}

6. 使用collect的三参数版本

// 更底层的实现方式
map<string, integer> manualmap = products.stream()
    .collect(
        hashmap::new, // 供应商:创建新的map
        (map, product) -> {
            // 累加器:处理每个元素
            string key = product.getname();
            int value = product.getquantity();
            map.merge(key, value, integer::sum); // 存在则求和,不存在则添加
        },
        hashmap::putall // 组合器:用于并行流
    );

7. 处理并发map

// 线程安全的concurrentmap
concurrentmap<string, integer> concurrentmap = products.stream()
    .collect(collectors.toconcurrentmap(
        product::getname,
        product::getquantity,
        integer::sum
    ));

8. 完整的实战示例

public class completemapexample {
    public static void main(string[] args) {
        list<transaction> transactions = arrays.aslist(
            new transaction("acc001", "deposit", 1000),
            new transaction("acc001", "withdraw", 200),
            new transaction("acc002", "deposit", 500),
            new transaction("acc001", "deposit", 300),
            new transaction("acc003", "deposit", 1500)
        );
        // 按账户分组,计算余额(存款为正,取款为负)
        map<string, double> accountbalances = transactions.stream()
            .collect(collectors.tomap(
                transaction::getaccountnumber,
                transaction -> {
                    double amount = transaction.getamount();
                    if ("withdraw".equals(transaction.gettype())) {
                        amount = -amount;
                    }
                    return amount;
                },
                double::sum // 存在则累加余额
            ));
        system.out.println("账户余额:");
        accountbalances.foreach((account, balance) -> 
            system.out.println(account + ": " + balance)
        );
    }
}
class transaction {
    private string accountnumber;
    private string type;
    private double amount;
    public transaction(string accountnumber, string type, double amount) {
        this.accountnumber = accountnumber;
        this.type = type;
        this.amount = amount;
    }
    // getters
}

关键总结

  1. collectors.tomap() 是主要工具,第三个参数是合并函数
  2. 合并函数 (oldvalue, newvalue) -> {...} 决定了存在时的更新策略
  3. 多种策略:覆盖、累加、取最大值、收集到列表等
  4. 线程安全:使用 toconcurrentmap() 处理并发场景
  5. 分组收集groupingby() 用于更复杂的分组操作

stream api 提供了非常强大的 map 操作能力,完全可以实现"存在则更新,不存在则添加"的需求!

到此这篇关于java中stream api处理map初始化的文章就介绍到这了,更多相关java stream api处理map初始化内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com