Java根据Bean实体某一属性获取Bean全部信息

该代码示例展示了一个Java类`CountryEnvironment`,包含国家的编码、名称、位置和简称等属性。类中使用一个ConcurrentHashMap存储基于国家简称的CountryEnvironment实例。静态方法`getCountryInformation`根据国家简称返回对应的CountryEnvironment对象。在主函数中,通过调用此方法测试了查询过程。

Java根据Bean实体某一属性获取Bean全部信息

业务场景

业务涉及到多个国家,现在需要根据国家的某一属性(以国家简称为例)获得国家的全部信息。

业务代码

package com.example.country;

import lombok.*;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@ToString
public class CountryEnvironment {

    @Getter
    private final Integer countryNumber;//国家编码

    @Getter
    private final String countryName;//国家名称

    @Getter
    private final String countryLocation;//国家位置

    @Getter
    private final String countryAbbreviation;//国家简称

    private CountryEnvironment(Integer countryNumber, String countryName, String countryLocation, String countryAbbreviation) {
        this.countryNumber = countryNumber;
        this.countryName = countryName;
        this.countryLocation = countryLocation;
        this.countryAbbreviation = countryAbbreviation;
    }

    private static final Map<String,CountryEnvironment> map = new ConcurrentHashMap<>();

    public static CountryEnvironment getCountryInformation(String countryAbbreviation) {

        if (map.get(countryAbbreviation) == null) {
            CountryEnvironment countryEnvironment;
            switch (countryAbbreviation) {
                case "UK":
                    countryEnvironment = new CountryEnvironment(22, "Britain", "Southern", "UK");
                    break;
                case "FR":
                    countryEnvironment = new CountryEnvironment(33, "France", "Northern", "FR");
                    break;
                default:
                    throw new RuntimeException();
            }
             map.put(countryAbbreviation, countryEnvironment);
        }
        return map.get(countryAbbreviation);
    }

    public static void main(String[] args) {
        //主函数测试
        CountryEnvironment countryEnvironment = getCountryInformation("UK");
        System.out.println(countryEnvironment);
    }
}

测试结果:

在这里插入图片描述

评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

YD_1989

分享不易,非常感谢您的鼓励支持

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值