2

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.

resueman
  • 10,572
  • 10
  • 31
  • 45
Soujanya
  • 277
  • 4
  • 17
  • 1
    Possible duplicate of [Convert a String to an enum in Java](http://stackoverflow.com/questions/604424/convert-a-string-to-an-enum-in-java) – wero Feb 25 '16 at 19:36
  • There's no direct way to do that. You'll have to iterate over each one, and compare your input with the price. – resueman Feb 25 '16 at 19:36
  • 1
    Iterate throuh all the cars, and find the one which has the price "900". – JB Nizet Feb 25 '16 at 19:37
  • ok,Thanks for the quick reply – Soujanya Feb 25 '16 at 19:37
  • @Soujanya look at http://stackoverflow.com/a/2965252/3215527 – wero Feb 25 '16 at 19:37
  • btw, the terminology in this question is a bit confusing. `"900"` isn't the "name" of the constructor, it's the (first, and only) _argument_ to the constructor. Constructors don't really have names (unlike methods), unless you're in the nitty-gritty world of reflection, in which case a constructor's name is always `""`. – yshavit Feb 25 '16 at 19:59

3 Answers3

6
Optional<Car> car = Arrays.stream(Car.values())
     .filter(c -> c.getPrice().equals(input))
     .findFirst();
andrucz
  • 1,971
  • 2
  • 18
  • 30
  • 2
    Excellent use of Java 8 Streams and the filter function @andrucz! @resueman was correct in the Question's comments. You must iterate over all of the elements and make the comparison. Java 8 streams has made this much easier though. – aaiezza Feb 25 '16 at 19:42
  • 1
    I like that it uses Optional. It handles the case that the user looks for a nonexistant price very well. – emory Feb 25 '16 at 19:45
2

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.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
1

This returns the name of the Enum:

Car.lamborghini.name();

Bifz
  • 403
  • 2
  • 9