Home > Enterprise >  How to filter get request by name and enums, when object is inside a HashMap?
How to filter get request by name and enums, when object is inside a HashMap?

Time:09-29

So I have an API that stores cards into a HashMap<Integer, Card>, I can send a GET to this API in two ways:

http://localhost:8080/app/cards - Will list me all cards (JSON) like:

[
{
    "atk": 5,
    "class": "QUALQUER",
    "def": 2,
    "desc": "UM TESTE REX CARD PRE-ALPHA EDITION",
    "id": 1,
    "name": "T-REX",
    "type": "CRIATURA"
},
{
    "atk": 5,
    "class": "QUALQUER",
    "def": 2,
    "desc": "UM TESTE REX CARD PRE-ALPHA EDITION",
    "id": 2,
    "name": "T-REX",
    "type": "CRIATURA"
}]

I can also get by ID with http://localhost:8080/app/cards/1 (1 is the ID)

My get by ID

@GET
@Path("{id}")
@Produces(MediaType.APPLICATION_JSON)
public Carta getById(@PathParam("id") int id) {
    return repositorio.getID(id);
}

However, I still need to create a GET by name, by type and by class. the name will retrieve only one result, but class and type are enums and I don't know how to filter each Card object inside the HashMap, since its a HashMap<Integer, Card>, the get by ID was easy. There is no need to create a database as this is an exercise, but everything I try fails, including creating the GET request, i'm starting by copying the above method and changing @Path to "name", but it gives me errors too.

Card class:

public class Card {

private int id;

private String name;
private String desc;
private int atk;
private int def;
private CardType type; //enum
private CardClass class;  //enum

CodePudding user response:

You can filter the HashMap using Java 8 streams:

List<Card> cards = cardsHashMap.entrySet().stream()
        //filter cards by type
        .filter(e -> Card.CRIATURA.equals(e.getValue().getType())) 
        //map to the corresponding Card object 
        .map(e -> new Card(...)) 
        .collect(Collectors.toList());
  • Related