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.
Optional<Car> car = Arrays.stream(Car.values())
.filter(c -> c.getPrice().equals(input))
.findFirst();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With