How do I get the index of an Item in a LinkedHashMap in a List?How do I sort a list of dictionaries by a value of the dictionary?What is the difference between Python's list methods append and extend?How do I read / convert an InputStream into a String in Java?How do I generate random integers within a specific range in Java?Difference between HashMap, LinkedHashMap and TreeMapHow to split a string in JavaHow to directly initialize a HashMap (in a literal way)?How to fix java.lang.UnsupportedClassVersionError: Unsupported major.minor versionJava 8 List<V> into Map<K, V>How to install Java 8 on Mac

Find max number you can create from an array of numbers

How to supply water to a coastal desert town with no rain and no freshwater aquifers?

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

Did William Shakespeare hide things in his writings?

How can a ban from entering the US be lifted?

Will electrically joined dipoles of different lengths, at right angles, behave as a multiband antenna?

How frequently do Russian people still refer to others by their patronymic (отчество)?

How to play a D major chord lower than the open E major chord on guitar?

What is the maximum amount of diamond in one Minecraft game?

Is there a standard definition of the "stall" phenomena?

Do Goblin tokens count as Goblins?

Do the 26 richest billionaires own as much wealth as the poorest 3.8 billion people?

Motorcyle Chain needs to be cleaned every time you lube it?

Isn't "Dave's protocol" good if only the database, and not the code, is leaked?

How do I check that users don't write down their passwords?

Why would "dead languages" be the only languages that spells could be written in?

Why did Super-VGA offer the 5:4 1280*1024 resolution?

Why is there paternal, for fatherly, fraternal, for brotherly, but no similar word for sons?

What is the shape of the upper boundary of water hitting a screen?

PhD: When to quit and move on?

What instances can be solved today by modern solvers (pure LP)?

Who is responsible for exterminating cockroaches in house - tenant or landlord?

LTSpice: how to setup sinusoidal or exponential voltage source?

Curve fitting when data has a sharp initial slope and then tapers off



How do I get the index of an Item in a LinkedHashMap in a List?


How do I sort a list of dictionaries by a value of the dictionary?What is the difference between Python's list methods append and extend?How do I read / convert an InputStream into a String in Java?How do I generate random integers within a specific range in Java?Difference between HashMap, LinkedHashMap and TreeMapHow to split a string in JavaHow to directly initialize a HashMap (in a literal way)?How to fix java.lang.UnsupportedClassVersionError: Unsupported major.minor versionJava 8 List<V> into Map<K, V>How to install Java 8 on Mac






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








-1















I have this Map



Map<String, List<OrderLine>> productsNeeded = new LinkedHashMap<>();


and I want to search in the List(s) for an Item, and then get the Key of the List where the Item was found.










share|improve this question
























  • Do you want to get the key or the index? If you want the key, this is a poor use of a map and you might be better off with a BiMap.

    – David Ehrmann
    Mar 25 at 19:24







  • 3





    You should really use a Map<OrderLine, String> instead of your map: a Map is used to find values by key, not vice versa.

    – JB Nizet
    Mar 25 at 19:25

















-1















I have this Map



Map<String, List<OrderLine>> productsNeeded = new LinkedHashMap<>();


and I want to search in the List(s) for an Item, and then get the Key of the List where the Item was found.










share|improve this question
























  • Do you want to get the key or the index? If you want the key, this is a poor use of a map and you might be better off with a BiMap.

    – David Ehrmann
    Mar 25 at 19:24







  • 3





    You should really use a Map<OrderLine, String> instead of your map: a Map is used to find values by key, not vice versa.

    – JB Nizet
    Mar 25 at 19:25













-1












-1








-1








I have this Map



Map<String, List<OrderLine>> productsNeeded = new LinkedHashMap<>();


and I want to search in the List(s) for an Item, and then get the Key of the List where the Item was found.










share|improve this question
















I have this Map



Map<String, List<OrderLine>> productsNeeded = new LinkedHashMap<>();


and I want to search in the List(s) for an Item, and then get the Key of the List where the Item was found.







java data-structures java-8 linkedhashmap






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 26 at 20:22









Andronicus

7,5793 gold badges20 silver badges36 bronze badges




7,5793 gold badges20 silver badges36 bronze badges










asked Mar 25 at 19:22









phil330dphil330d

111 silver badge4 bronze badges




111 silver badge4 bronze badges












  • Do you want to get the key or the index? If you want the key, this is a poor use of a map and you might be better off with a BiMap.

    – David Ehrmann
    Mar 25 at 19:24







  • 3





    You should really use a Map<OrderLine, String> instead of your map: a Map is used to find values by key, not vice versa.

    – JB Nizet
    Mar 25 at 19:25

















  • Do you want to get the key or the index? If you want the key, this is a poor use of a map and you might be better off with a BiMap.

    – David Ehrmann
    Mar 25 at 19:24







  • 3





    You should really use a Map<OrderLine, String> instead of your map: a Map is used to find values by key, not vice versa.

    – JB Nizet
    Mar 25 at 19:25
















Do you want to get the key or the index? If you want the key, this is a poor use of a map and you might be better off with a BiMap.

– David Ehrmann
Mar 25 at 19:24






Do you want to get the key or the index? If you want the key, this is a poor use of a map and you might be better off with a BiMap.

– David Ehrmann
Mar 25 at 19:24





3




3





You should really use a Map<OrderLine, String> instead of your map: a Map is used to find values by key, not vice versa.

– JB Nizet
Mar 25 at 19:25





You should really use a Map<OrderLine, String> instead of your map: a Map is used to find values by key, not vice versa.

– JB Nizet
Mar 25 at 19:25












2 Answers
2






active

oldest

votes


















1














You can try this:



 productsNeeded.entrySet().stream()
.filter(e -> e.getValue()
.contains(matchingElement))
.map(Map.Entry::getKey)
.findFirst();


Provided that matchingElement is the object of type OrderLine you're looking for. Here you're getting Optional. To get value you can call get or orElse to provide a default one, for example:



 productsNeeded.entrySet().stream()
.filter(e -> e.getValue()
.contains(matchingElement))
.map(Map.Entry::getKey)
.findFirst().orElse(null);





share|improve this answer






























    1














    You can do this with Streams in Java 8+. I simplified this by making the inner key a List<String>:



    String item = "";
    Map<String, List<String>> productsNeeded = new LinkedHashMap<>();
    String key = productsNeeded.entrySet().stream()
    .filter(e -> e.getValue().stream().anyMatch(item::equals))
    //Or e -> e.getValue().contains(item)
    .map(Entry::getKey)
    .findFirst()
    .orElse("");


    Where you can put something else in the default value of orElse.






    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%2f55345045%2fhow-do-i-get-the-index-of-an-item-in-a-linkedhashmap-in-a-list%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









      1














      You can try this:



       productsNeeded.entrySet().stream()
      .filter(e -> e.getValue()
      .contains(matchingElement))
      .map(Map.Entry::getKey)
      .findFirst();


      Provided that matchingElement is the object of type OrderLine you're looking for. Here you're getting Optional. To get value you can call get or orElse to provide a default one, for example:



       productsNeeded.entrySet().stream()
      .filter(e -> e.getValue()
      .contains(matchingElement))
      .map(Map.Entry::getKey)
      .findFirst().orElse(null);





      share|improve this answer



























        1














        You can try this:



         productsNeeded.entrySet().stream()
        .filter(e -> e.getValue()
        .contains(matchingElement))
        .map(Map.Entry::getKey)
        .findFirst();


        Provided that matchingElement is the object of type OrderLine you're looking for. Here you're getting Optional. To get value you can call get or orElse to provide a default one, for example:



         productsNeeded.entrySet().stream()
        .filter(e -> e.getValue()
        .contains(matchingElement))
        .map(Map.Entry::getKey)
        .findFirst().orElse(null);





        share|improve this answer

























          1












          1








          1







          You can try this:



           productsNeeded.entrySet().stream()
          .filter(e -> e.getValue()
          .contains(matchingElement))
          .map(Map.Entry::getKey)
          .findFirst();


          Provided that matchingElement is the object of type OrderLine you're looking for. Here you're getting Optional. To get value you can call get or orElse to provide a default one, for example:



           productsNeeded.entrySet().stream()
          .filter(e -> e.getValue()
          .contains(matchingElement))
          .map(Map.Entry::getKey)
          .findFirst().orElse(null);





          share|improve this answer













          You can try this:



           productsNeeded.entrySet().stream()
          .filter(e -> e.getValue()
          .contains(matchingElement))
          .map(Map.Entry::getKey)
          .findFirst();


          Provided that matchingElement is the object of type OrderLine you're looking for. Here you're getting Optional. To get value you can call get or orElse to provide a default one, for example:



           productsNeeded.entrySet().stream()
          .filter(e -> e.getValue()
          .contains(matchingElement))
          .map(Map.Entry::getKey)
          .findFirst().orElse(null);






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Mar 25 at 19:25









          AndronicusAndronicus

          7,5793 gold badges20 silver badges36 bronze badges




          7,5793 gold badges20 silver badges36 bronze badges























              1














              You can do this with Streams in Java 8+. I simplified this by making the inner key a List<String>:



              String item = "";
              Map<String, List<String>> productsNeeded = new LinkedHashMap<>();
              String key = productsNeeded.entrySet().stream()
              .filter(e -> e.getValue().stream().anyMatch(item::equals))
              //Or e -> e.getValue().contains(item)
              .map(Entry::getKey)
              .findFirst()
              .orElse("");


              Where you can put something else in the default value of orElse.






              share|improve this answer





























                1














                You can do this with Streams in Java 8+. I simplified this by making the inner key a List<String>:



                String item = "";
                Map<String, List<String>> productsNeeded = new LinkedHashMap<>();
                String key = productsNeeded.entrySet().stream()
                .filter(e -> e.getValue().stream().anyMatch(item::equals))
                //Or e -> e.getValue().contains(item)
                .map(Entry::getKey)
                .findFirst()
                .orElse("");


                Where you can put something else in the default value of orElse.






                share|improve this answer



























                  1












                  1








                  1







                  You can do this with Streams in Java 8+. I simplified this by making the inner key a List<String>:



                  String item = "";
                  Map<String, List<String>> productsNeeded = new LinkedHashMap<>();
                  String key = productsNeeded.entrySet().stream()
                  .filter(e -> e.getValue().stream().anyMatch(item::equals))
                  //Or e -> e.getValue().contains(item)
                  .map(Entry::getKey)
                  .findFirst()
                  .orElse("");


                  Where you can put something else in the default value of orElse.






                  share|improve this answer















                  You can do this with Streams in Java 8+. I simplified this by making the inner key a List<String>:



                  String item = "";
                  Map<String, List<String>> productsNeeded = new LinkedHashMap<>();
                  String key = productsNeeded.entrySet().stream()
                  .filter(e -> e.getValue().stream().anyMatch(item::equals))
                  //Or e -> e.getValue().contains(item)
                  .map(Entry::getKey)
                  .findFirst()
                  .orElse("");


                  Where you can put something else in the default value of orElse.







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Mar 25 at 19:34

























                  answered Mar 25 at 19:26









                  GBlodgettGBlodgett

                  11.8k4 gold badges22 silver badges38 bronze badges




                  11.8k4 gold badges22 silver badges38 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%2f55345045%2fhow-do-i-get-the-index-of-an-item-in-a-linkedhashmap-in-a-list%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

                      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

                      용인 삼성생명 블루밍스 목차 통계 역대 감독 선수단 응원단 경기장 같이 보기 외부 링크 둘러보기 메뉴samsungblueminx.comeh선수 명단용인 삼성생명 블루밍스용인 삼성생명 블루밍스ehsamsungblueminx.comeheheheh

                      155 수학 과학 기타 둘러보기 메뉴eh추가해eh문서를 완성해