You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为存储在HashMap中的Card对象实现按名称和枚举字段过滤的GET接口

解决方案

一、路径匹配问题修复

你之前修改@Path为name时报错,是因为现有@Path("{id}")是通配型路径参数,会优先匹配所有/cards/后跟任意字符串的请求,把name当作ID参数值触发类型转换错误。最简单的适配方案是给所有单条件查询接口加上固定路径前缀,避免匹配冲突:

  • 原ID查询路径调整为:/cards/id/{id}
  • 名称查询路径:/cards/name/{name}
  • 类型查询路径:/cards/type/{type}
  • 职业查询路径:/cards/class/{cardClass}

二、接口实现+HashMap过滤代码

直接遍历HashMap的values()集合配合Stream流即可完成过滤,枚举类型JAX-RS会自动完成字符串到枚举值的转换:

import java.util.List;
import java.util.stream.Collectors;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import com.fasterxml.jackson.annotation.JsonProperty;

// 调整原有ID查询接口路径
@GET
@Path("/id/{id}")
@Produces(MediaType.APPLICATION_JSON)
public Card getById(@PathParam("id") int id) {
    return repositorio.get(id);
}

// 1. 按名称查询(返回单条结果)
@GET
@Path("/name/{name}")
@Produces(MediaType.APPLICATION_JSON)
public Card getByName(@PathParam("name") String name) {
    return repositorio.values().stream()
            .filter(card -> name.equals(card.getName()))
            .findFirst()
            .orElse(null); // 无匹配时返回null,也可自定义404响应逻辑
}

// 2. 按类型查询(枚举类型,返回匹配列表)
@GET
@Path("/type/{type}")
@Produces(MediaType.APPLICATION_JSON)
public List<Card> getByType(@PathParam("type") CardType type) {
    return repositorio.values().stream()
            .filter(card -> type.equals(card.getType()))
            .collect(Collectors.toList());
}

// 3. 按职业查询(注意class是Java关键字,需调整Card类字段名)
@GET
@Path("/class/{cardClass}")
@Produces(MediaType.APPLICATION_JSON)
public List<Card> getByClass(@PathParam("cardClass") CardClass cardClass) {
    return repositorio.values().stream()
            .filter(card -> cardClass.equals(card.getCardClass()))
            .collect(Collectors.toList());
}

三、补充说明

  • 你给出的Card类中字段名使用了Java保留关键字class,会触发编译错误,建议将字段重命名为cardClass,同时添加@JsonProperty("class")注解,保证JSON输出的字段名和原有格式一致。
  • 如果不想调整原有ID查询路径,也可以用查询参数实现过滤,比如请求路径为/cards?name=T-REX,代码中用@QueryParam接收参数即可,不会和路径参数产生冲突。
  • 如果需要名称模糊匹配,将filter中的判断逻辑改为card.getName().contains(name)即可。

内容的提问来源于stack exchange,提问作者Kalil

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 11:18:03