Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get enum constructor name from value in java?

Tags:

java

I have enum like below

enum Car {
    lamborghini("900"),tata("2"),audi("50"),fiat("15"),honda("12");
    private String price;
    Car(String p) {
        price = p;
    }
    String getPrice() {
        return price;
    } 
}

public class Main {
    public static void main(String args[]){
        System.out.println("All car prices:");
        System.out.println(Car.valueOf("lamborghini").getPrice());

        for (Car c : Car.values())
            System.out.println(c + " costs " 
                               + c.getPrice() + " thousand dollars.");
    }
}

This is working fine,But I have Input like "900" ,So I want to get that enumConstructorName like lamborghini ,How can I do this.

like image 336
Soujanya Avatar asked Aug 29 '26 22:08

Soujanya


2 Answers

Optional<Car> car = Arrays.stream(Car.values())
     .filter(c -> c.getPrice().equals(input))
     .findFirst();
like image 198
andrucz Avatar answered Sep 01 '26 17:09

andrucz


The most efficient way is to have a Map you can lookup.

static final Map<String, Car> priceMap = values().stream()
                                    .collect(Collectors.toMap(c -> c.getPrice(), c -> c));

public static Car lookupPrice(String s) {
    return priceMap.get(s);
}

However, I would store a number in a field like int or double.

like image 32
Peter Lawrey Avatar answered Sep 01 '26 16:09

Peter Lawrey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!