Java开发

对象列表根据对象key分组转换为字典

2023-08-14  本文已影响0人  _浅墨_
方法一、常规实现方式
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        List<Customer> customerList = new ArrayList<>();
        // 添加示例数据
        customerList.add(new Customer("John", "1234567890"));
        customerList.add(new Customer("Alice", "0987654321"));
        customerList.add(new Customer("Bob", "1234567890"));
        customerList.add(new Customer("Eve", "9876543210"));

        Map<String, List<Customer>> dictionary = generateDictionary(customerList);
        System.out.println(dictionary);
    }

    public static Map<String, List<Customer>> generateDictionary(List<Customer> customerList) {
        Map<String, List<Customer>> dictionary = new HashMap<>();

        for (Customer customer : customerList) {
            String phoneNo = customer.getPhoneNo();

            if (dictionary.containsKey(phoneNo)) {
                dictionary.get(phoneNo).add(customer);
            } else {
                List<Customer> newList = new ArrayList<>();
                newList.add(customer);
                dictionary.put(phoneNo, newList);
            }
        }

        return dictionary;
    }
}

class Customer {
    private String name;
    private String phoneNo;

    public Customer(String name, String phoneNo) {
        this.name = name;
        this.phoneNo = phoneNo;
    }

    public String getPhoneNo() {
        return phoneNo;
    }

    @Override
    public String toString() {
        return name;
    }
}

在上述示例代码中,我们创建了一个 Customer 类来表示客户对象,并在 Main 类中实现了 generateDictionary() 方法来生成字典。通过示例数据,我们展示了如何使用该方法来生成具有相同 phoneNo 的客户对象列表的字典。

方法二、优雅方法

以下是使用 Java 实现您所描述问题的示例代码:

import java.util.*;
import java.util.stream.Collectors;
// 假设你有一个Customer类,每个对象都有一个phoneNo属性
class Customer {
    private String phoneNo;
    public Customer(String phoneNo) {
        this.phoneNo = phoneNo;
    }
    public String getPhoneNo() {
        return phoneNo;
    }
}

// 假设你有一个customer list,每个对象都是Customer类的实例
List<Customer> customer_list = Arrays.asList(new Customer("123"), new Customer("456"), new Customer("123"), new Customer("789"));

// 你可以使用stream()和Collectors.groupingBy()来创建一个字典,key为phoneNo,value为手机号为phoneNo的customer对象list
Map<String, List<Customer>> result = customer_list.stream().collect(Collectors.groupingBy(Customer::getPhoneNo));

// 打印结果
System.out.println(result);

上一篇 下一篇

猜你喜欢

热点阅读