Home > Back-end >  How can i display an enum without all informations
How can i display an enum without all informations

Time:11-12

Hello i have a Planet class like below and i want to display Enum like MERCURY EARTH Etc ... without the informations between parenthesis and i'm using the CommonName inside the parenthesis like MERCURE , TERRE to search and display the Enum

public  enum Planet {

    MERCURY(0.387,"MERCURE") , VENUS(0.722,"VÉNUS"), EARTH(1.0,"TERRE"), MARS(1.52,"MARS"), JUPITER(5.20,"JUPITER"),
    SATURN(9.58,"SATURNE"),  URANUS(19.2,"URANUS"),  NEPTUNE(30.1,"NEPTUNE");
    private double  distance;
    private String commonName;
    




    
    private Planet(double v, String c) {
        distance = v;
        commonName = c;
    }

    public  double getDistanceFromTheSunInAstronomicalUnit(double distance) {
        return distance;
    }


    public  String getCommonName() {
        return commonName;
    }

    @Override //
    public  String toString() {
        return "" commonName  " (" distance ")";
    }
}

And i have this function

 Optional <Planet> Dept = Arrays.stream(Planet.values())
                        .filter(e -> e.getCommonName().equals(Dep))
                        .findFirst();

                System.out.println(Dept.get());

i'm trying to display the Enum without the informations between the parenthesis and comparing the CommonName with an input(Dept) but the problem is everytime i get the informations inside the parenthesis

Anyone can help me please ?

CodePudding user response:

When printing the enum value directly, as you have found it prints information along with it. If you just want the name of the enum, e.g. "MARS", try using the name method, which returns a string of name.

Example: System.out.println(Dept.get().name());

CodePudding user response:

try this:

Planet Dept = 
Arrays.stream(Planet.values())
.filter(e -> e.getCommonName().equals(Dep))
.findFirst().get();

 System.out.println(Dept);

CodePudding user response:

You can search value like this:

public static void main(String[] args) {
    Optional <Planet> Dept = Arrays.stream(Planet.values())
            .filter(e -> e.name()==Planet.MERCURY.name())
            .findFirst();

    System.out.println(Dept.get());
}

Or Like This:

public static void main(String[] args) {
    String valueYouSearch="MERCURY";
    Optional <Planet> Dept = Arrays.stream(Planet.values())
            .filter(e -> e==Planet.valueOf(valueYouSearch))
            .findFirst();

    System.out.println(Dept.get());
}
  • Related