最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

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

 更新時間:2025年10月10日 14:42:26   作者:BirdMan98  
Stream API提供了多種方式來實(shí)現(xiàn)Map的構(gòu)建、存在則更新、不存在則添加的操作,本文通過實(shí)例代碼介紹Java中Stream API處理Map初始化的操作方法,感興趣的朋友一起看看吧

當(dāng)然可以! Stream API 提供了多種方式來實(shí)現(xiàn) Map 的構(gòu)建、存在則更新、不存在則添加的操作。以下是幾種常用的方法:

1. 使用Collectors.toMap()處理重復(fù)鍵

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), // 重復(fù)的key
            new Person("Charlie", 35)
        );
        // 方法1: 使用toMap的合并函數(shù)來處理重復(fù)鍵
        Map<String, Integer> personMap = people.stream()
            .collect(Collectors.toMap(
                Person::getName,      // key映射器
                Person::getAge,       // value映射器
                (existing, newValue) -> newValue // 合并函數(shù):新值覆蓋舊值
            ));
        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. 不同的合并策略

// 合并函數(shù)的不同實(shí)現(xiàn)策略
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. 復(fù)雜的對象操作

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) // 重復(fù)商品,價格不同
        );
        // 按商品名稱分組,計算總價值(價格*數(shù)量)
        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操作(更復(fù)雜的邏輯)

// 如果存在則更新,不存在則添加的復(fù)雜邏輯
Map<String, ProductStats> productStatsMap = products.stream()
    .collect(Collectors.toMap(
        Product::getName,
        product -> new ProductStats(1, product.getPrice() * product.getQuantity(), product.getPrice()),
        (existingStats, newStats) -> {
            // 存在則更新:數(shù)量累加,總價值累加,價格取平均值
            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的三參數(shù)版本

// 更底層的實(shí)現(xiàn)方式
Map<String, Integer> manualMap = products.stream()
    .collect(
        HashMap::new, // 供應(yīng)商:創(chuàng)建新的Map
        (map, product) -> {
            // 累加器:處理每個元素
            String key = product.getName();
            int value = product.getQuantity();
            map.merge(key, value, Integer::sum); // 存在則求和,不存在則添加
        },
        HashMap::putAll // 組合器:用于并行流
    );

7. 處理并發(fā)Map

// 線程安全的ConcurrentMap
ConcurrentMap<String, Integer> concurrentMap = products.stream()
    .collect(Collectors.toConcurrentMap(
        Product::getName,
        Product::getQuantity,
        Integer::sum
    ));

8. 完整的實(shí)戰(zhàn)示例

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)
        );
        // 按賬戶分組,計算余額(存款為正,取款為負(fù))
        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
}

關(guān)鍵總結(jié)

  1. Collectors.toMap() 是主要工具,第三個參數(shù)是合并函數(shù)
  2. 合并函數(shù) (oldValue, newValue) -> {...} 決定了存在時的更新策略
  3. 多種策略:覆蓋、累加、取最大值、收集到列表等
  4. 線程安全:使用 toConcurrentMap() 處理并發(fā)場景
  5. 分組收集groupingBy() 用于更復(fù)雜的分組操作

Stream API 提供了非常強(qiáng)大的 Map 操作能力,完全可以實(shí)現(xiàn)"存在則更新,不存在則添加"的需求!

到此這篇關(guān)于Java中Stream API處理Map初始化的文章就介紹到這了,更多相關(guān)Java Stream API處理Map初始化內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論

布尔津县| 阿勒泰市| 辽宁省| 吉水县| 靖宇县| 甘谷县| 抚宁县| 马关县| 孝昌县| 隆安县| 房产| 象州县| 无为县| 深圳市| 宜州市| 电白县| 南平市| 彭阳县| 建始县| 和硕县| 盐亭县| 博爱县| 武邑县| 南投县| 龙井市| 和龙市| 巢湖市| 克东县| 阿拉尔市| 逊克县| 东安县| 白山市| 夏津县| 唐海县| 阳朔县| 育儿| 洛南县| 衡东县| 东源县| 靖边县| 荥经县|