List key value with unique key as an object or enumIs Java “pass-by-reference” or “pass-by-value”?How do I check if a list is empty?Sort a Map<Key, Value> by valuesFinding the index of an item given a list containing it in PythonWhat is the difference between Python's list methods append and extend?How to get an enum value from a string value in Java?How to make a flat list out of list of listsHow do I get the number of elements in a list?How do I concatenate two lists in Python?How to clone or copy a list?

Construction of the word подтвержда́ть

Can the word "coexist" be used for more than two things/people/subjects/... etc?

Why is the saxophone not common in classical repertoire?

what is the meaning of "stock" dilution on the Massive Dev Chart Website?

My mother co-signed for my car. Can she take it away from me if I am the one making car payments?

SQL Server error 242 with ANSI datetime

How long had Bertha Mason been in the attic at the point of the events in Jane Eyre

Did Winston Churchill praise Rolls-Royce engines?

How might boat designs change in order to allow them to be pulled by dragons?

Is it possible that Curiosity measured its own methane or failed doing the spectrometry?

Language Selector

Why did my leaking pool light trip the circuit breaker, but not the GFCI?

3D nonogram – What's going on?

Finding integer database columns that may have their data type changed to reduce size

Should I cheat if the majority does it?

What does the ash content of broken wheat really mean?

Who are the police in Hong Kong?

List of Implementations for common OR problems

Is it possible to spoof an IP address to an exact number?

What do you call the angle of the direction of an airplane?

Are there advantages in writing by hand over typing out a story?

When should we use dependency injection (C#)

What is the right way to query an I2C device from an interrupt service routine?

Go function to test whether a file exists



List key value with unique key as an object or enum


Is Java “pass-by-reference” or “pass-by-value”?How do I check if a list is empty?Sort a Map<Key, Value> by valuesFinding the index of an item given a list containing it in PythonWhat is the difference between Python's list methods append and extend?How to get an enum value from a string value in Java?How to make a flat list out of list of listsHow do I get the number of elements in a list?How do I concatenate two lists in Python?How to clone or copy a list?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








0















Question



  • I would like a list of key value pair such as a HashMap for instance or other if recommended.


  • This list should contains unique keys objects used to retrieve the values.


  • Keys should NOT be a STRING, since string is not unique and any value can be passed.


  • Also constants are limited and are using the concepts of strings as well and should not be considered.


Example



  • What is wanted is for instance list[Color.Red] = "Red".


  • At this stage, i have created an enum containing all the keys.
    For instance enum ColorRED,BLUE then add it to a new HashMap.


  • So the only way to retrieve a color, is to use the enum as a key list[Color.RED].


Implementation



public final static Map<Color, String> colors = new HashMap<>();
public final static enum ColorRED, BLUE;
static

colors.put(RED, "red");
colors.put(BLUE, "blue");

public static string getColor(Color color)

return colors.get(color);



Need Help



Is there a type of Collection in Java that could do the job ?
If not then what might be the best practice to do so ?










share|improve this question
























  • Is your example real in that you want Color.RED to return the value of "Red"? Because you can override the .toString() or add a method to the enum to return a particular value, and enums are an array, and unique. But using an enum as a key is a perfectly legitimate way to constrain the input.

    – KevinO
    Mar 25 at 18:15











  • You can use constructor of enum to add a value, so mapping is essential.

    – Roman C
    Mar 25 at 19:15











  • yes you are right that was the way to do it, i have added a potential solution at the end of this thread. cheers !

    – fra
    Apr 1 at 18:21

















0















Question



  • I would like a list of key value pair such as a HashMap for instance or other if recommended.


  • This list should contains unique keys objects used to retrieve the values.


  • Keys should NOT be a STRING, since string is not unique and any value can be passed.


  • Also constants are limited and are using the concepts of strings as well and should not be considered.


Example



  • What is wanted is for instance list[Color.Red] = "Red".


  • At this stage, i have created an enum containing all the keys.
    For instance enum ColorRED,BLUE then add it to a new HashMap.


  • So the only way to retrieve a color, is to use the enum as a key list[Color.RED].


Implementation



public final static Map<Color, String> colors = new HashMap<>();
public final static enum ColorRED, BLUE;
static

colors.put(RED, "red");
colors.put(BLUE, "blue");

public static string getColor(Color color)

return colors.get(color);



Need Help



Is there a type of Collection in Java that could do the job ?
If not then what might be the best practice to do so ?










share|improve this question
























  • Is your example real in that you want Color.RED to return the value of "Red"? Because you can override the .toString() or add a method to the enum to return a particular value, and enums are an array, and unique. But using an enum as a key is a perfectly legitimate way to constrain the input.

    – KevinO
    Mar 25 at 18:15











  • You can use constructor of enum to add a value, so mapping is essential.

    – Roman C
    Mar 25 at 19:15











  • yes you are right that was the way to do it, i have added a potential solution at the end of this thread. cheers !

    – fra
    Apr 1 at 18:21













0












0








0








Question



  • I would like a list of key value pair such as a HashMap for instance or other if recommended.


  • This list should contains unique keys objects used to retrieve the values.


  • Keys should NOT be a STRING, since string is not unique and any value can be passed.


  • Also constants are limited and are using the concepts of strings as well and should not be considered.


Example



  • What is wanted is for instance list[Color.Red] = "Red".


  • At this stage, i have created an enum containing all the keys.
    For instance enum ColorRED,BLUE then add it to a new HashMap.


  • So the only way to retrieve a color, is to use the enum as a key list[Color.RED].


Implementation



public final static Map<Color, String> colors = new HashMap<>();
public final static enum ColorRED, BLUE;
static

colors.put(RED, "red");
colors.put(BLUE, "blue");

public static string getColor(Color color)

return colors.get(color);



Need Help



Is there a type of Collection in Java that could do the job ?
If not then what might be the best practice to do so ?










share|improve this question
















Question



  • I would like a list of key value pair such as a HashMap for instance or other if recommended.


  • This list should contains unique keys objects used to retrieve the values.


  • Keys should NOT be a STRING, since string is not unique and any value can be passed.


  • Also constants are limited and are using the concepts of strings as well and should not be considered.


Example



  • What is wanted is for instance list[Color.Red] = "Red".


  • At this stage, i have created an enum containing all the keys.
    For instance enum ColorRED,BLUE then add it to a new HashMap.


  • So the only way to retrieve a color, is to use the enum as a key list[Color.RED].


Implementation



public final static Map<Color, String> colors = new HashMap<>();
public final static enum ColorRED, BLUE;
static

colors.put(RED, "red");
colors.put(BLUE, "blue");

public static string getColor(Color color)

return colors.get(color);



Need Help



Is there a type of Collection in Java that could do the job ?
If not then what might be the best practice to do so ?







java list collections hashmap






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 25 at 20:33









Rajkumar Natarajan

2,1881 gold badge20 silver badges49 bronze badges




2,1881 gold badge20 silver badges49 bronze badges










asked Mar 25 at 18:09









frafra

176 bronze badges




176 bronze badges












  • Is your example real in that you want Color.RED to return the value of "Red"? Because you can override the .toString() or add a method to the enum to return a particular value, and enums are an array, and unique. But using an enum as a key is a perfectly legitimate way to constrain the input.

    – KevinO
    Mar 25 at 18:15











  • You can use constructor of enum to add a value, so mapping is essential.

    – Roman C
    Mar 25 at 19:15











  • yes you are right that was the way to do it, i have added a potential solution at the end of this thread. cheers !

    – fra
    Apr 1 at 18:21

















  • Is your example real in that you want Color.RED to return the value of "Red"? Because you can override the .toString() or add a method to the enum to return a particular value, and enums are an array, and unique. But using an enum as a key is a perfectly legitimate way to constrain the input.

    – KevinO
    Mar 25 at 18:15











  • You can use constructor of enum to add a value, so mapping is essential.

    – Roman C
    Mar 25 at 19:15











  • yes you are right that was the way to do it, i have added a potential solution at the end of this thread. cheers !

    – fra
    Apr 1 at 18:21
















Is your example real in that you want Color.RED to return the value of "Red"? Because you can override the .toString() or add a method to the enum to return a particular value, and enums are an array, and unique. But using an enum as a key is a perfectly legitimate way to constrain the input.

– KevinO
Mar 25 at 18:15





Is your example real in that you want Color.RED to return the value of "Red"? Because you can override the .toString() or add a method to the enum to return a particular value, and enums are an array, and unique. But using an enum as a key is a perfectly legitimate way to constrain the input.

– KevinO
Mar 25 at 18:15













You can use constructor of enum to add a value, so mapping is essential.

– Roman C
Mar 25 at 19:15





You can use constructor of enum to add a value, so mapping is essential.

– Roman C
Mar 25 at 19:15













yes you are right that was the way to do it, i have added a potential solution at the end of this thread. cheers !

– fra
Apr 1 at 18:21





yes you are right that was the way to do it, i have added a potential solution at the end of this thread. cheers !

– fra
Apr 1 at 18:21












2 Answers
2






active

oldest

votes


















0














The keys are unique in all maps. Add duplicate key, then it will be overwritten.. The difference between the various maps implementations concern the possibility of null keys, the order of iteration and concurrency issues.



exemple:



Map hm = new HashMap();
hm.put("1", new Integer(1));
hm.put("2", new Integer(2));
hm.put("3", new Integer(3));
hm.put("4", new Integer(4));
hm.put("1", new Integer(5));// value integer 1 is overwritten by 5


In addition, Map key are generic, you can put what you want, not only String, exemple:



Map<Integer, String> hm = new HashMap<>();
hm.put(10, "1");





share|improve this answer























  • Thank you @davidr, in your example you can basically try to retrieve values that does not exists in your List. This is the problem we try to solve. For instance hm.get(12); won't return any value. We are trying to force the developer to enter only values that exist by using an enum as a key value pair. Your answer does not answer the question.

    – fra
    Mar 25 at 21:39


















0














Potential Solution



After checking around enum and its possibilities, there is a way to assign values to a Key in an enum, like follow.



  • Create a new enum and assign Key such as public enum ColorRED;.

  • Add a constructor parameter to it such as public enum ColorRED("red");

  • Add a constructor to the enum such as public enum ColorRED("red"); Color()

  • Add a new field inside enum called value such as private String value; public String getValue() return value;

  • Set field value in constructor of enum such as Color(String value) this.value = value;

  • Enum work in that way, for each Key you add it creates a new instance field String value linked to the Key, then it will use the constructor you have declared to save the value.

Full Implementation



public enum Color

//[PROP]
RED("red"),
GREEN("green"),
BLUE("blue");

private String value;
public String getValue return value;

//[BUILD]
Color(String value) this.value = value;

//[UTIL]
Color[] getKeys() return this.values; //values method is already a method existing in enum class, we are just proposing another method name here as a facade for simplicity.



  • If we want to retrieve an item we just simply do Color.RED.value, in this way only existing keys returned wanted value.

  • Note that value doesn't needs to be the name of the key but could be a totally different value.

Please comment if you have any simpler solution without putting more complexity to the solution.






share|improve this answer

























    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55344073%2flist-key-value-with-unique-key-as-an-object-or-enum%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    The keys are unique in all maps. Add duplicate key, then it will be overwritten.. The difference between the various maps implementations concern the possibility of null keys, the order of iteration and concurrency issues.



    exemple:



    Map hm = new HashMap();
    hm.put("1", new Integer(1));
    hm.put("2", new Integer(2));
    hm.put("3", new Integer(3));
    hm.put("4", new Integer(4));
    hm.put("1", new Integer(5));// value integer 1 is overwritten by 5


    In addition, Map key are generic, you can put what you want, not only String, exemple:



    Map<Integer, String> hm = new HashMap<>();
    hm.put(10, "1");





    share|improve this answer























    • Thank you @davidr, in your example you can basically try to retrieve values that does not exists in your List. This is the problem we try to solve. For instance hm.get(12); won't return any value. We are trying to force the developer to enter only values that exist by using an enum as a key value pair. Your answer does not answer the question.

      – fra
      Mar 25 at 21:39















    0














    The keys are unique in all maps. Add duplicate key, then it will be overwritten.. The difference between the various maps implementations concern the possibility of null keys, the order of iteration and concurrency issues.



    exemple:



    Map hm = new HashMap();
    hm.put("1", new Integer(1));
    hm.put("2", new Integer(2));
    hm.put("3", new Integer(3));
    hm.put("4", new Integer(4));
    hm.put("1", new Integer(5));// value integer 1 is overwritten by 5


    In addition, Map key are generic, you can put what you want, not only String, exemple:



    Map<Integer, String> hm = new HashMap<>();
    hm.put(10, "1");





    share|improve this answer























    • Thank you @davidr, in your example you can basically try to retrieve values that does not exists in your List. This is the problem we try to solve. For instance hm.get(12); won't return any value. We are trying to force the developer to enter only values that exist by using an enum as a key value pair. Your answer does not answer the question.

      – fra
      Mar 25 at 21:39













    0












    0








    0







    The keys are unique in all maps. Add duplicate key, then it will be overwritten.. The difference between the various maps implementations concern the possibility of null keys, the order of iteration and concurrency issues.



    exemple:



    Map hm = new HashMap();
    hm.put("1", new Integer(1));
    hm.put("2", new Integer(2));
    hm.put("3", new Integer(3));
    hm.put("4", new Integer(4));
    hm.put("1", new Integer(5));// value integer 1 is overwritten by 5


    In addition, Map key are generic, you can put what you want, not only String, exemple:



    Map<Integer, String> hm = new HashMap<>();
    hm.put(10, "1");





    share|improve this answer













    The keys are unique in all maps. Add duplicate key, then it will be overwritten.. The difference between the various maps implementations concern the possibility of null keys, the order of iteration and concurrency issues.



    exemple:



    Map hm = new HashMap();
    hm.put("1", new Integer(1));
    hm.put("2", new Integer(2));
    hm.put("3", new Integer(3));
    hm.put("4", new Integer(4));
    hm.put("1", new Integer(5));// value integer 1 is overwritten by 5


    In addition, Map key are generic, you can put what you want, not only String, exemple:



    Map<Integer, String> hm = new HashMap<>();
    hm.put(10, "1");






    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Mar 25 at 18:17









    davidrdavidr

    724 bronze badges




    724 bronze badges












    • Thank you @davidr, in your example you can basically try to retrieve values that does not exists in your List. This is the problem we try to solve. For instance hm.get(12); won't return any value. We are trying to force the developer to enter only values that exist by using an enum as a key value pair. Your answer does not answer the question.

      – fra
      Mar 25 at 21:39

















    • Thank you @davidr, in your example you can basically try to retrieve values that does not exists in your List. This is the problem we try to solve. For instance hm.get(12); won't return any value. We are trying to force the developer to enter only values that exist by using an enum as a key value pair. Your answer does not answer the question.

      – fra
      Mar 25 at 21:39
















    Thank you @davidr, in your example you can basically try to retrieve values that does not exists in your List. This is the problem we try to solve. For instance hm.get(12); won't return any value. We are trying to force the developer to enter only values that exist by using an enum as a key value pair. Your answer does not answer the question.

    – fra
    Mar 25 at 21:39





    Thank you @davidr, in your example you can basically try to retrieve values that does not exists in your List. This is the problem we try to solve. For instance hm.get(12); won't return any value. We are trying to force the developer to enter only values that exist by using an enum as a key value pair. Your answer does not answer the question.

    – fra
    Mar 25 at 21:39













    0














    Potential Solution



    After checking around enum and its possibilities, there is a way to assign values to a Key in an enum, like follow.



    • Create a new enum and assign Key such as public enum ColorRED;.

    • Add a constructor parameter to it such as public enum ColorRED("red");

    • Add a constructor to the enum such as public enum ColorRED("red"); Color()

    • Add a new field inside enum called value such as private String value; public String getValue() return value;

    • Set field value in constructor of enum such as Color(String value) this.value = value;

    • Enum work in that way, for each Key you add it creates a new instance field String value linked to the Key, then it will use the constructor you have declared to save the value.

    Full Implementation



    public enum Color

    //[PROP]
    RED("red"),
    GREEN("green"),
    BLUE("blue");

    private String value;
    public String getValue return value;

    //[BUILD]
    Color(String value) this.value = value;

    //[UTIL]
    Color[] getKeys() return this.values; //values method is already a method existing in enum class, we are just proposing another method name here as a facade for simplicity.



    • If we want to retrieve an item we just simply do Color.RED.value, in this way only existing keys returned wanted value.

    • Note that value doesn't needs to be the name of the key but could be a totally different value.

    Please comment if you have any simpler solution without putting more complexity to the solution.






    share|improve this answer



























      0














      Potential Solution



      After checking around enum and its possibilities, there is a way to assign values to a Key in an enum, like follow.



      • Create a new enum and assign Key such as public enum ColorRED;.

      • Add a constructor parameter to it such as public enum ColorRED("red");

      • Add a constructor to the enum such as public enum ColorRED("red"); Color()

      • Add a new field inside enum called value such as private String value; public String getValue() return value;

      • Set field value in constructor of enum such as Color(String value) this.value = value;

      • Enum work in that way, for each Key you add it creates a new instance field String value linked to the Key, then it will use the constructor you have declared to save the value.

      Full Implementation



      public enum Color

      //[PROP]
      RED("red"),
      GREEN("green"),
      BLUE("blue");

      private String value;
      public String getValue return value;

      //[BUILD]
      Color(String value) this.value = value;

      //[UTIL]
      Color[] getKeys() return this.values; //values method is already a method existing in enum class, we are just proposing another method name here as a facade for simplicity.



      • If we want to retrieve an item we just simply do Color.RED.value, in this way only existing keys returned wanted value.

      • Note that value doesn't needs to be the name of the key but could be a totally different value.

      Please comment if you have any simpler solution without putting more complexity to the solution.






      share|improve this answer

























        0












        0








        0







        Potential Solution



        After checking around enum and its possibilities, there is a way to assign values to a Key in an enum, like follow.



        • Create a new enum and assign Key such as public enum ColorRED;.

        • Add a constructor parameter to it such as public enum ColorRED("red");

        • Add a constructor to the enum such as public enum ColorRED("red"); Color()

        • Add a new field inside enum called value such as private String value; public String getValue() return value;

        • Set field value in constructor of enum such as Color(String value) this.value = value;

        • Enum work in that way, for each Key you add it creates a new instance field String value linked to the Key, then it will use the constructor you have declared to save the value.

        Full Implementation



        public enum Color

        //[PROP]
        RED("red"),
        GREEN("green"),
        BLUE("blue");

        private String value;
        public String getValue return value;

        //[BUILD]
        Color(String value) this.value = value;

        //[UTIL]
        Color[] getKeys() return this.values; //values method is already a method existing in enum class, we are just proposing another method name here as a facade for simplicity.



        • If we want to retrieve an item we just simply do Color.RED.value, in this way only existing keys returned wanted value.

        • Note that value doesn't needs to be the name of the key but could be a totally different value.

        Please comment if you have any simpler solution without putting more complexity to the solution.






        share|improve this answer













        Potential Solution



        After checking around enum and its possibilities, there is a way to assign values to a Key in an enum, like follow.



        • Create a new enum and assign Key such as public enum ColorRED;.

        • Add a constructor parameter to it such as public enum ColorRED("red");

        • Add a constructor to the enum such as public enum ColorRED("red"); Color()

        • Add a new field inside enum called value such as private String value; public String getValue() return value;

        • Set field value in constructor of enum such as Color(String value) this.value = value;

        • Enum work in that way, for each Key you add it creates a new instance field String value linked to the Key, then it will use the constructor you have declared to save the value.

        Full Implementation



        public enum Color

        //[PROP]
        RED("red"),
        GREEN("green"),
        BLUE("blue");

        private String value;
        public String getValue return value;

        //[BUILD]
        Color(String value) this.value = value;

        //[UTIL]
        Color[] getKeys() return this.values; //values method is already a method existing in enum class, we are just proposing another method name here as a facade for simplicity.



        • If we want to retrieve an item we just simply do Color.RED.value, in this way only existing keys returned wanted value.

        • Note that value doesn't needs to be the name of the key but could be a totally different value.

        Please comment if you have any simpler solution without putting more complexity to the solution.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Mar 25 at 21:57









        frafra

        176 bronze badges




        176 bronze badges



























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55344073%2flist-key-value-with-unique-key-as-an-object-or-enum%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

            SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

            은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현