Check the keys in the map matching with the List content in Java












13















I have a List of Strings and a Map. Every key in the map needs to present in the list else I need to throw an exception. As of now I am looping the list and checking the key and throw exception if the map doesn't contains the key. Below is the sample code is what I am doing. IS there any other way in Java8 we can do it in one line or something using streams and filters ?



And also the contents in the list and keys in the map should match. That I am already handling in the separate if condition.



import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class TestClass {

public static void main(String args) {

List<String> ll = new ArrayList<>();
Map<String, Integer> m = new HashMap<>();
ll.add("a");
ll.add("b");
ll.add("d");

m.put("a", 1);
m.put("b", 1);
m.put("c", 1);

if(ll.size() != m.size){
System.out.println("Throw Exception");
}

for(String s : ll) {

if(!m.containsKey(s)) {
System.out.println("Throw Exception");
}
}
}
}









share|improve this question




















  • 2





    You are saying different things in your question and in your code. In your question you said you want to check if every key is in the list, but in the code, you are checking if everything in the list is present in the map.

    – Sweeper
    yesterday











  • How about this ll.stream().filter(s -> !m.containsKey(s)).forEach(s -> { throw new RuntimeException("Not found"); }); ?

    – manfromnowhere
    yesterday













  • @Sweeper Sorry , I will modify the question. Technically, the contents in the list and keys in the map should match.

    – sparker
    yesterday






  • 2





    If they really need to match, then test something like m.keySet().equals(new HashSet<>(ll)). Or maybe keep the required keys in a set in the first place.

    – Stuart Marks
    yesterday






  • 1





    @sparker Seems like what you are expecting your code does is not what it actually is doing. Maybe think about it and rephrase the question to clear out the doubt.

    – nullpointer
    yesterday
















13















I have a List of Strings and a Map. Every key in the map needs to present in the list else I need to throw an exception. As of now I am looping the list and checking the key and throw exception if the map doesn't contains the key. Below is the sample code is what I am doing. IS there any other way in Java8 we can do it in one line or something using streams and filters ?



And also the contents in the list and keys in the map should match. That I am already handling in the separate if condition.



import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class TestClass {

public static void main(String args) {

List<String> ll = new ArrayList<>();
Map<String, Integer> m = new HashMap<>();
ll.add("a");
ll.add("b");
ll.add("d");

m.put("a", 1);
m.put("b", 1);
m.put("c", 1);

if(ll.size() != m.size){
System.out.println("Throw Exception");
}

for(String s : ll) {

if(!m.containsKey(s)) {
System.out.println("Throw Exception");
}
}
}
}









share|improve this question




















  • 2





    You are saying different things in your question and in your code. In your question you said you want to check if every key is in the list, but in the code, you are checking if everything in the list is present in the map.

    – Sweeper
    yesterday











  • How about this ll.stream().filter(s -> !m.containsKey(s)).forEach(s -> { throw new RuntimeException("Not found"); }); ?

    – manfromnowhere
    yesterday













  • @Sweeper Sorry , I will modify the question. Technically, the contents in the list and keys in the map should match.

    – sparker
    yesterday






  • 2





    If they really need to match, then test something like m.keySet().equals(new HashSet<>(ll)). Or maybe keep the required keys in a set in the first place.

    – Stuart Marks
    yesterday






  • 1





    @sparker Seems like what you are expecting your code does is not what it actually is doing. Maybe think about it and rephrase the question to clear out the doubt.

    – nullpointer
    yesterday














13












13








13


1






I have a List of Strings and a Map. Every key in the map needs to present in the list else I need to throw an exception. As of now I am looping the list and checking the key and throw exception if the map doesn't contains the key. Below is the sample code is what I am doing. IS there any other way in Java8 we can do it in one line or something using streams and filters ?



And also the contents in the list and keys in the map should match. That I am already handling in the separate if condition.



import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class TestClass {

public static void main(String args) {

List<String> ll = new ArrayList<>();
Map<String, Integer> m = new HashMap<>();
ll.add("a");
ll.add("b");
ll.add("d");

m.put("a", 1);
m.put("b", 1);
m.put("c", 1);

if(ll.size() != m.size){
System.out.println("Throw Exception");
}

for(String s : ll) {

if(!m.containsKey(s)) {
System.out.println("Throw Exception");
}
}
}
}









share|improve this question
















I have a List of Strings and a Map. Every key in the map needs to present in the list else I need to throw an exception. As of now I am looping the list and checking the key and throw exception if the map doesn't contains the key. Below is the sample code is what I am doing. IS there any other way in Java8 we can do it in one line or something using streams and filters ?



And also the contents in the list and keys in the map should match. That I am already handling in the separate if condition.



import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class TestClass {

public static void main(String args) {

List<String> ll = new ArrayList<>();
Map<String, Integer> m = new HashMap<>();
ll.add("a");
ll.add("b");
ll.add("d");

m.put("a", 1);
m.put("b", 1);
m.put("c", 1);

if(ll.size() != m.size){
System.out.println("Throw Exception");
}

for(String s : ll) {

if(!m.containsKey(s)) {
System.out.println("Throw Exception");
}
}
}
}






java lambda java-8 java-stream






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited yesterday







sparker

















asked yesterday









sparkersparker

326414




326414








  • 2





    You are saying different things in your question and in your code. In your question you said you want to check if every key is in the list, but in the code, you are checking if everything in the list is present in the map.

    – Sweeper
    yesterday











  • How about this ll.stream().filter(s -> !m.containsKey(s)).forEach(s -> { throw new RuntimeException("Not found"); }); ?

    – manfromnowhere
    yesterday













  • @Sweeper Sorry , I will modify the question. Technically, the contents in the list and keys in the map should match.

    – sparker
    yesterday






  • 2





    If they really need to match, then test something like m.keySet().equals(new HashSet<>(ll)). Or maybe keep the required keys in a set in the first place.

    – Stuart Marks
    yesterday






  • 1





    @sparker Seems like what you are expecting your code does is not what it actually is doing. Maybe think about it and rephrase the question to clear out the doubt.

    – nullpointer
    yesterday














  • 2





    You are saying different things in your question and in your code. In your question you said you want to check if every key is in the list, but in the code, you are checking if everything in the list is present in the map.

    – Sweeper
    yesterday











  • How about this ll.stream().filter(s -> !m.containsKey(s)).forEach(s -> { throw new RuntimeException("Not found"); }); ?

    – manfromnowhere
    yesterday













  • @Sweeper Sorry , I will modify the question. Technically, the contents in the list and keys in the map should match.

    – sparker
    yesterday






  • 2





    If they really need to match, then test something like m.keySet().equals(new HashSet<>(ll)). Or maybe keep the required keys in a set in the first place.

    – Stuart Marks
    yesterday






  • 1





    @sparker Seems like what you are expecting your code does is not what it actually is doing. Maybe think about it and rephrase the question to clear out the doubt.

    – nullpointer
    yesterday








2




2





You are saying different things in your question and in your code. In your question you said you want to check if every key is in the list, but in the code, you are checking if everything in the list is present in the map.

– Sweeper
yesterday





You are saying different things in your question and in your code. In your question you said you want to check if every key is in the list, but in the code, you are checking if everything in the list is present in the map.

– Sweeper
yesterday













How about this ll.stream().filter(s -> !m.containsKey(s)).forEach(s -> { throw new RuntimeException("Not found"); }); ?

– manfromnowhere
yesterday







How about this ll.stream().filter(s -> !m.containsKey(s)).forEach(s -> { throw new RuntimeException("Not found"); }); ?

– manfromnowhere
yesterday















@Sweeper Sorry , I will modify the question. Technically, the contents in the list and keys in the map should match.

– sparker
yesterday





@Sweeper Sorry , I will modify the question. Technically, the contents in the list and keys in the map should match.

– sparker
yesterday




2




2





If they really need to match, then test something like m.keySet().equals(new HashSet<>(ll)). Or maybe keep the required keys in a set in the first place.

– Stuart Marks
yesterday





If they really need to match, then test something like m.keySet().equals(new HashSet<>(ll)). Or maybe keep the required keys in a set in the first place.

– Stuart Marks
yesterday




1




1





@sparker Seems like what you are expecting your code does is not what it actually is doing. Maybe think about it and rephrase the question to clear out the doubt.

– nullpointer
yesterday





@sparker Seems like what you are expecting your code does is not what it actually is doing. Maybe think about it and rephrase the question to clear out the doubt.

– nullpointer
yesterday












6 Answers
6






active

oldest

votes


















9















Every key in the map needs to present in the list else I need to throw
an exception




You could do it using Stream.anyMatch and iterating on the keyset of the map instead as (variable names updated for readability purpose) :



if(map.keySet().stream().anyMatch(key -> !list.contains(key))) {
throw new CustomException("");
}


Better and as simple as it gets, use List.containsAll :



if(!list.containsAll(map.keySet())) {
throw new CustomException("");
}


Important: If you can trade for O(n) space to reduce the runtime complexity, you can create a HashSet out of your List and then perform the lookups. It would reduce the runtime complexity from O(n^2) to O(n) and the implementation would look like:



Set<String> allUniqueElementsInList = new HashSet<>(list);
if(!allUniqueElementsInList.containsAll(map.keySet())) {
throw new CustomException("");
}





share|improve this answer





















  • 1





    Or if(! map.keySet().stream().allMatch(list::contains)), but of course, if(!list.containsAll(map.keySet())) is the canonical solution.

    – Holger
    yesterday



















2














Try this:



if ((ll == null && m == null) ||                            // if both are null
((ll.size() == m.size() && m.keySet().containsAll(ll))) // or contain the same elements
) {
System.out.println("Collections contain the same elements");
} else {
throw new CustomException("Collections don't match!");
}





share|improve this answer































    2














    We can try adding the list to a set, then comparing that set with the keyset from your hashmap:



    List<String> ll = new ArrayList<>();
    ll.add("a");
    ll.add("b");
    ll.add("d");

    Map<String, Integer> m = new HashMap<>();
    m.put("a", 1);
    m.put("b", 1);
    m.put("c", 1);

    Set<String> set = new HashSet<String>(ll);

    if (Objects.equals(set, m.keySet())) {
    System.out.println("sets match");
    }
    else {
    System.out.println("sets do not match");
    }





    share|improve this answer





















    • 1





      I think OP is looking for an answer wrt to java-8 (something using streams and filters) here.

      – Nicholas K
      yesterday








    • 1





      @NicholasK well there is nothing in the code here, that doesn't work with java8., right? But yeah the throwing of exception is definitely missing and also an unwanted creation of Set which doesn't seem to be required for the purpose of OP.

      – nullpointer
      yesterday








    • 1





      Ummm... if (...m.keySet() == null ...) ... what is that? The keySet can never be null, and in any case: the comparison of the size() and the containsAll call boil down to a simple if (Objects.equals(m.keySet(), set)) ...

      – Marco13
      yesterday











    • @MarcoPolo Thanks for the feedback, answer updated.

      – Tim Biegeleisen
      yesterday



















    1














    Simply use the following :-



    m.keySet().stream().filter(e -> !ll.contains(e)).findAny()
    .ifPresent(e -> throwException("Key Not found : " + e));


    And define the throwException method below :



    public static void throwException(String msg) {
    throw new RuntimeException(msg);
    }





    share|improve this answer

































      0














      You can simply change your existing code to -



      if(!m.keySet().containsAll(ll)) {
      System.out.println("Throws Exception");
      }


      This will solve your problem. :)






      share|improve this answer





















      • 2





        This logic has a problem. Should the hashmap's keyset contain extra items, your code would still return true. Also, if null on both sides of the comparison means equal, then you would have to cover that case as well.

        – Tim Biegeleisen
        yesterday











      • @p.bansal - The same check performed in reverse was what OP is mostly trying to look forward to.

        – nullpointer
        yesterday






      • 1





        @nullpointer This matches the OP’s code but not the text in the question, which requests the reverse. So +1 from me on this answer. But then the OP said in comments that the map keys must match the list, a yet again different check. (Sigh.)

        – Stuart Marks
        yesterday











      • @StuartMarks well, if they must match, I’d use if(m.size() != ll.size() || !m.keySet().containsAll(ll)), as I suppose, m.keySet().containsAll(ll) is potentially faster than ll.containsAll(m.keySet())

        – Holger
        yesterday











      • @Holger At the time this answer was written, it matched the code in the question. The OP subsequently changed the requirements.

        – Stuart Marks
        yesterday



















      0














      Here is another solution:



          if (ll  .parallelStream()
      .filter(v -> !m.containsKey(v)) // Filter alle values not contained in the map
      .count() == 0) { // If no values are left then every key was present
      // do something
      } else {
      throw new RuntimeException("hello");
      }


      Just wanted to show a different approach






      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%2f54141672%2fcheck-the-keys-in-the-map-matching-with-the-list-content-in-java%23new-answer', 'question_page');
        }
        );

        Post as a guest















        Required, but never shown

























        6 Answers
        6






        active

        oldest

        votes








        6 Answers
        6






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        9















        Every key in the map needs to present in the list else I need to throw
        an exception




        You could do it using Stream.anyMatch and iterating on the keyset of the map instead as (variable names updated for readability purpose) :



        if(map.keySet().stream().anyMatch(key -> !list.contains(key))) {
        throw new CustomException("");
        }


        Better and as simple as it gets, use List.containsAll :



        if(!list.containsAll(map.keySet())) {
        throw new CustomException("");
        }


        Important: If you can trade for O(n) space to reduce the runtime complexity, you can create a HashSet out of your List and then perform the lookups. It would reduce the runtime complexity from O(n^2) to O(n) and the implementation would look like:



        Set<String> allUniqueElementsInList = new HashSet<>(list);
        if(!allUniqueElementsInList.containsAll(map.keySet())) {
        throw new CustomException("");
        }





        share|improve this answer





















        • 1





          Or if(! map.keySet().stream().allMatch(list::contains)), but of course, if(!list.containsAll(map.keySet())) is the canonical solution.

          – Holger
          yesterday
















        9















        Every key in the map needs to present in the list else I need to throw
        an exception




        You could do it using Stream.anyMatch and iterating on the keyset of the map instead as (variable names updated for readability purpose) :



        if(map.keySet().stream().anyMatch(key -> !list.contains(key))) {
        throw new CustomException("");
        }


        Better and as simple as it gets, use List.containsAll :



        if(!list.containsAll(map.keySet())) {
        throw new CustomException("");
        }


        Important: If you can trade for O(n) space to reduce the runtime complexity, you can create a HashSet out of your List and then perform the lookups. It would reduce the runtime complexity from O(n^2) to O(n) and the implementation would look like:



        Set<String> allUniqueElementsInList = new HashSet<>(list);
        if(!allUniqueElementsInList.containsAll(map.keySet())) {
        throw new CustomException("");
        }





        share|improve this answer





















        • 1





          Or if(! map.keySet().stream().allMatch(list::contains)), but of course, if(!list.containsAll(map.keySet())) is the canonical solution.

          – Holger
          yesterday














        9












        9








        9








        Every key in the map needs to present in the list else I need to throw
        an exception




        You could do it using Stream.anyMatch and iterating on the keyset of the map instead as (variable names updated for readability purpose) :



        if(map.keySet().stream().anyMatch(key -> !list.contains(key))) {
        throw new CustomException("");
        }


        Better and as simple as it gets, use List.containsAll :



        if(!list.containsAll(map.keySet())) {
        throw new CustomException("");
        }


        Important: If you can trade for O(n) space to reduce the runtime complexity, you can create a HashSet out of your List and then perform the lookups. It would reduce the runtime complexity from O(n^2) to O(n) and the implementation would look like:



        Set<String> allUniqueElementsInList = new HashSet<>(list);
        if(!allUniqueElementsInList.containsAll(map.keySet())) {
        throw new CustomException("");
        }





        share|improve this answer
















        Every key in the map needs to present in the list else I need to throw
        an exception




        You could do it using Stream.anyMatch and iterating on the keyset of the map instead as (variable names updated for readability purpose) :



        if(map.keySet().stream().anyMatch(key -> !list.contains(key))) {
        throw new CustomException("");
        }


        Better and as simple as it gets, use List.containsAll :



        if(!list.containsAll(map.keySet())) {
        throw new CustomException("");
        }


        Important: If you can trade for O(n) space to reduce the runtime complexity, you can create a HashSet out of your List and then perform the lookups. It would reduce the runtime complexity from O(n^2) to O(n) and the implementation would look like:



        Set<String> allUniqueElementsInList = new HashSet<>(list);
        if(!allUniqueElementsInList.containsAll(map.keySet())) {
        throw new CustomException("");
        }






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited yesterday

























        answered yesterday









        nullpointernullpointer

        44.9k1096184




        44.9k1096184








        • 1





          Or if(! map.keySet().stream().allMatch(list::contains)), but of course, if(!list.containsAll(map.keySet())) is the canonical solution.

          – Holger
          yesterday














        • 1





          Or if(! map.keySet().stream().allMatch(list::contains)), but of course, if(!list.containsAll(map.keySet())) is the canonical solution.

          – Holger
          yesterday








        1




        1





        Or if(! map.keySet().stream().allMatch(list::contains)), but of course, if(!list.containsAll(map.keySet())) is the canonical solution.

        – Holger
        yesterday





        Or if(! map.keySet().stream().allMatch(list::contains)), but of course, if(!list.containsAll(map.keySet())) is the canonical solution.

        – Holger
        yesterday













        2














        Try this:



        if ((ll == null && m == null) ||                            // if both are null
        ((ll.size() == m.size() && m.keySet().containsAll(ll))) // or contain the same elements
        ) {
        System.out.println("Collections contain the same elements");
        } else {
        throw new CustomException("Collections don't match!");
        }





        share|improve this answer




























          2














          Try this:



          if ((ll == null && m == null) ||                            // if both are null
          ((ll.size() == m.size() && m.keySet().containsAll(ll))) // or contain the same elements
          ) {
          System.out.println("Collections contain the same elements");
          } else {
          throw new CustomException("Collections don't match!");
          }





          share|improve this answer


























            2












            2








            2







            Try this:



            if ((ll == null && m == null) ||                            // if both are null
            ((ll.size() == m.size() && m.keySet().containsAll(ll))) // or contain the same elements
            ) {
            System.out.println("Collections contain the same elements");
            } else {
            throw new CustomException("Collections don't match!");
            }





            share|improve this answer













            Try this:



            if ((ll == null && m == null) ||                            // if both are null
            ((ll.size() == m.size() && m.keySet().containsAll(ll))) // or contain the same elements
            ) {
            System.out.println("Collections contain the same elements");
            } else {
            throw new CustomException("Collections don't match!");
            }






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered yesterday









            ETOETO

            2,106423




            2,106423























                2














                We can try adding the list to a set, then comparing that set with the keyset from your hashmap:



                List<String> ll = new ArrayList<>();
                ll.add("a");
                ll.add("b");
                ll.add("d");

                Map<String, Integer> m = new HashMap<>();
                m.put("a", 1);
                m.put("b", 1);
                m.put("c", 1);

                Set<String> set = new HashSet<String>(ll);

                if (Objects.equals(set, m.keySet())) {
                System.out.println("sets match");
                }
                else {
                System.out.println("sets do not match");
                }





                share|improve this answer





















                • 1





                  I think OP is looking for an answer wrt to java-8 (something using streams and filters) here.

                  – Nicholas K
                  yesterday








                • 1





                  @NicholasK well there is nothing in the code here, that doesn't work with java8., right? But yeah the throwing of exception is definitely missing and also an unwanted creation of Set which doesn't seem to be required for the purpose of OP.

                  – nullpointer
                  yesterday








                • 1





                  Ummm... if (...m.keySet() == null ...) ... what is that? The keySet can never be null, and in any case: the comparison of the size() and the containsAll call boil down to a simple if (Objects.equals(m.keySet(), set)) ...

                  – Marco13
                  yesterday











                • @MarcoPolo Thanks for the feedback, answer updated.

                  – Tim Biegeleisen
                  yesterday
















                2














                We can try adding the list to a set, then comparing that set with the keyset from your hashmap:



                List<String> ll = new ArrayList<>();
                ll.add("a");
                ll.add("b");
                ll.add("d");

                Map<String, Integer> m = new HashMap<>();
                m.put("a", 1);
                m.put("b", 1);
                m.put("c", 1);

                Set<String> set = new HashSet<String>(ll);

                if (Objects.equals(set, m.keySet())) {
                System.out.println("sets match");
                }
                else {
                System.out.println("sets do not match");
                }





                share|improve this answer





















                • 1





                  I think OP is looking for an answer wrt to java-8 (something using streams and filters) here.

                  – Nicholas K
                  yesterday








                • 1





                  @NicholasK well there is nothing in the code here, that doesn't work with java8., right? But yeah the throwing of exception is definitely missing and also an unwanted creation of Set which doesn't seem to be required for the purpose of OP.

                  – nullpointer
                  yesterday








                • 1





                  Ummm... if (...m.keySet() == null ...) ... what is that? The keySet can never be null, and in any case: the comparison of the size() and the containsAll call boil down to a simple if (Objects.equals(m.keySet(), set)) ...

                  – Marco13
                  yesterday











                • @MarcoPolo Thanks for the feedback, answer updated.

                  – Tim Biegeleisen
                  yesterday














                2












                2








                2







                We can try adding the list to a set, then comparing that set with the keyset from your hashmap:



                List<String> ll = new ArrayList<>();
                ll.add("a");
                ll.add("b");
                ll.add("d");

                Map<String, Integer> m = new HashMap<>();
                m.put("a", 1);
                m.put("b", 1);
                m.put("c", 1);

                Set<String> set = new HashSet<String>(ll);

                if (Objects.equals(set, m.keySet())) {
                System.out.println("sets match");
                }
                else {
                System.out.println("sets do not match");
                }





                share|improve this answer















                We can try adding the list to a set, then comparing that set with the keyset from your hashmap:



                List<String> ll = new ArrayList<>();
                ll.add("a");
                ll.add("b");
                ll.add("d");

                Map<String, Integer> m = new HashMap<>();
                m.put("a", 1);
                m.put("b", 1);
                m.put("c", 1);

                Set<String> set = new HashSet<String>(ll);

                if (Objects.equals(set, m.keySet())) {
                System.out.println("sets match");
                }
                else {
                System.out.println("sets do not match");
                }






                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited yesterday

























                answered yesterday









                Tim BiegeleisenTim Biegeleisen

                219k1388141




                219k1388141








                • 1





                  I think OP is looking for an answer wrt to java-8 (something using streams and filters) here.

                  – Nicholas K
                  yesterday








                • 1





                  @NicholasK well there is nothing in the code here, that doesn't work with java8., right? But yeah the throwing of exception is definitely missing and also an unwanted creation of Set which doesn't seem to be required for the purpose of OP.

                  – nullpointer
                  yesterday








                • 1





                  Ummm... if (...m.keySet() == null ...) ... what is that? The keySet can never be null, and in any case: the comparison of the size() and the containsAll call boil down to a simple if (Objects.equals(m.keySet(), set)) ...

                  – Marco13
                  yesterday











                • @MarcoPolo Thanks for the feedback, answer updated.

                  – Tim Biegeleisen
                  yesterday














                • 1





                  I think OP is looking for an answer wrt to java-8 (something using streams and filters) here.

                  – Nicholas K
                  yesterday








                • 1





                  @NicholasK well there is nothing in the code here, that doesn't work with java8., right? But yeah the throwing of exception is definitely missing and also an unwanted creation of Set which doesn't seem to be required for the purpose of OP.

                  – nullpointer
                  yesterday








                • 1





                  Ummm... if (...m.keySet() == null ...) ... what is that? The keySet can never be null, and in any case: the comparison of the size() and the containsAll call boil down to a simple if (Objects.equals(m.keySet(), set)) ...

                  – Marco13
                  yesterday











                • @MarcoPolo Thanks for the feedback, answer updated.

                  – Tim Biegeleisen
                  yesterday








                1




                1





                I think OP is looking for an answer wrt to java-8 (something using streams and filters) here.

                – Nicholas K
                yesterday







                I think OP is looking for an answer wrt to java-8 (something using streams and filters) here.

                – Nicholas K
                yesterday






                1




                1





                @NicholasK well there is nothing in the code here, that doesn't work with java8., right? But yeah the throwing of exception is definitely missing and also an unwanted creation of Set which doesn't seem to be required for the purpose of OP.

                – nullpointer
                yesterday







                @NicholasK well there is nothing in the code here, that doesn't work with java8., right? But yeah the throwing of exception is definitely missing and also an unwanted creation of Set which doesn't seem to be required for the purpose of OP.

                – nullpointer
                yesterday






                1




                1





                Ummm... if (...m.keySet() == null ...) ... what is that? The keySet can never be null, and in any case: the comparison of the size() and the containsAll call boil down to a simple if (Objects.equals(m.keySet(), set)) ...

                – Marco13
                yesterday





                Ummm... if (...m.keySet() == null ...) ... what is that? The keySet can never be null, and in any case: the comparison of the size() and the containsAll call boil down to a simple if (Objects.equals(m.keySet(), set)) ...

                – Marco13
                yesterday













                @MarcoPolo Thanks for the feedback, answer updated.

                – Tim Biegeleisen
                yesterday





                @MarcoPolo Thanks for the feedback, answer updated.

                – Tim Biegeleisen
                yesterday











                1














                Simply use the following :-



                m.keySet().stream().filter(e -> !ll.contains(e)).findAny()
                .ifPresent(e -> throwException("Key Not found : " + e));


                And define the throwException method below :



                public static void throwException(String msg) {
                throw new RuntimeException(msg);
                }





                share|improve this answer






























                  1














                  Simply use the following :-



                  m.keySet().stream().filter(e -> !ll.contains(e)).findAny()
                  .ifPresent(e -> throwException("Key Not found : " + e));


                  And define the throwException method below :



                  public static void throwException(String msg) {
                  throw new RuntimeException(msg);
                  }





                  share|improve this answer




























                    1












                    1








                    1







                    Simply use the following :-



                    m.keySet().stream().filter(e -> !ll.contains(e)).findAny()
                    .ifPresent(e -> throwException("Key Not found : " + e));


                    And define the throwException method below :



                    public static void throwException(String msg) {
                    throw new RuntimeException(msg);
                    }





                    share|improve this answer















                    Simply use the following :-



                    m.keySet().stream().filter(e -> !ll.contains(e)).findAny()
                    .ifPresent(e -> throwException("Key Not found : " + e));


                    And define the throwException method below :



                    public static void throwException(String msg) {
                    throw new RuntimeException(msg);
                    }






                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited yesterday

























                    answered yesterday









                    Nicholas KNicholas K

                    6,19751031




                    6,19751031























                        0














                        You can simply change your existing code to -



                        if(!m.keySet().containsAll(ll)) {
                        System.out.println("Throws Exception");
                        }


                        This will solve your problem. :)






                        share|improve this answer





















                        • 2





                          This logic has a problem. Should the hashmap's keyset contain extra items, your code would still return true. Also, if null on both sides of the comparison means equal, then you would have to cover that case as well.

                          – Tim Biegeleisen
                          yesterday











                        • @p.bansal - The same check performed in reverse was what OP is mostly trying to look forward to.

                          – nullpointer
                          yesterday






                        • 1





                          @nullpointer This matches the OP’s code but not the text in the question, which requests the reverse. So +1 from me on this answer. But then the OP said in comments that the map keys must match the list, a yet again different check. (Sigh.)

                          – Stuart Marks
                          yesterday











                        • @StuartMarks well, if they must match, I’d use if(m.size() != ll.size() || !m.keySet().containsAll(ll)), as I suppose, m.keySet().containsAll(ll) is potentially faster than ll.containsAll(m.keySet())

                          – Holger
                          yesterday











                        • @Holger At the time this answer was written, it matched the code in the question. The OP subsequently changed the requirements.

                          – Stuart Marks
                          yesterday
















                        0














                        You can simply change your existing code to -



                        if(!m.keySet().containsAll(ll)) {
                        System.out.println("Throws Exception");
                        }


                        This will solve your problem. :)






                        share|improve this answer





















                        • 2





                          This logic has a problem. Should the hashmap's keyset contain extra items, your code would still return true. Also, if null on both sides of the comparison means equal, then you would have to cover that case as well.

                          – Tim Biegeleisen
                          yesterday











                        • @p.bansal - The same check performed in reverse was what OP is mostly trying to look forward to.

                          – nullpointer
                          yesterday






                        • 1





                          @nullpointer This matches the OP’s code but not the text in the question, which requests the reverse. So +1 from me on this answer. But then the OP said in comments that the map keys must match the list, a yet again different check. (Sigh.)

                          – Stuart Marks
                          yesterday











                        • @StuartMarks well, if they must match, I’d use if(m.size() != ll.size() || !m.keySet().containsAll(ll)), as I suppose, m.keySet().containsAll(ll) is potentially faster than ll.containsAll(m.keySet())

                          – Holger
                          yesterday











                        • @Holger At the time this answer was written, it matched the code in the question. The OP subsequently changed the requirements.

                          – Stuart Marks
                          yesterday














                        0












                        0








                        0







                        You can simply change your existing code to -



                        if(!m.keySet().containsAll(ll)) {
                        System.out.println("Throws Exception");
                        }


                        This will solve your problem. :)






                        share|improve this answer















                        You can simply change your existing code to -



                        if(!m.keySet().containsAll(ll)) {
                        System.out.println("Throws Exception");
                        }


                        This will solve your problem. :)







                        share|improve this answer














                        share|improve this answer



                        share|improve this answer








                        edited yesterday









                        nullpointer

                        44.9k1096184




                        44.9k1096184










                        answered yesterday









                        p.bansalp.bansal

                        954




                        954








                        • 2





                          This logic has a problem. Should the hashmap's keyset contain extra items, your code would still return true. Also, if null on both sides of the comparison means equal, then you would have to cover that case as well.

                          – Tim Biegeleisen
                          yesterday











                        • @p.bansal - The same check performed in reverse was what OP is mostly trying to look forward to.

                          – nullpointer
                          yesterday






                        • 1





                          @nullpointer This matches the OP’s code but not the text in the question, which requests the reverse. So +1 from me on this answer. But then the OP said in comments that the map keys must match the list, a yet again different check. (Sigh.)

                          – Stuart Marks
                          yesterday











                        • @StuartMarks well, if they must match, I’d use if(m.size() != ll.size() || !m.keySet().containsAll(ll)), as I suppose, m.keySet().containsAll(ll) is potentially faster than ll.containsAll(m.keySet())

                          – Holger
                          yesterday











                        • @Holger At the time this answer was written, it matched the code in the question. The OP subsequently changed the requirements.

                          – Stuart Marks
                          yesterday














                        • 2





                          This logic has a problem. Should the hashmap's keyset contain extra items, your code would still return true. Also, if null on both sides of the comparison means equal, then you would have to cover that case as well.

                          – Tim Biegeleisen
                          yesterday











                        • @p.bansal - The same check performed in reverse was what OP is mostly trying to look forward to.

                          – nullpointer
                          yesterday






                        • 1





                          @nullpointer This matches the OP’s code but not the text in the question, which requests the reverse. So +1 from me on this answer. But then the OP said in comments that the map keys must match the list, a yet again different check. (Sigh.)

                          – Stuart Marks
                          yesterday











                        • @StuartMarks well, if they must match, I’d use if(m.size() != ll.size() || !m.keySet().containsAll(ll)), as I suppose, m.keySet().containsAll(ll) is potentially faster than ll.containsAll(m.keySet())

                          – Holger
                          yesterday











                        • @Holger At the time this answer was written, it matched the code in the question. The OP subsequently changed the requirements.

                          – Stuart Marks
                          yesterday








                        2




                        2





                        This logic has a problem. Should the hashmap's keyset contain extra items, your code would still return true. Also, if null on both sides of the comparison means equal, then you would have to cover that case as well.

                        – Tim Biegeleisen
                        yesterday





                        This logic has a problem. Should the hashmap's keyset contain extra items, your code would still return true. Also, if null on both sides of the comparison means equal, then you would have to cover that case as well.

                        – Tim Biegeleisen
                        yesterday













                        @p.bansal - The same check performed in reverse was what OP is mostly trying to look forward to.

                        – nullpointer
                        yesterday





                        @p.bansal - The same check performed in reverse was what OP is mostly trying to look forward to.

                        – nullpointer
                        yesterday




                        1




                        1





                        @nullpointer This matches the OP’s code but not the text in the question, which requests the reverse. So +1 from me on this answer. But then the OP said in comments that the map keys must match the list, a yet again different check. (Sigh.)

                        – Stuart Marks
                        yesterday





                        @nullpointer This matches the OP’s code but not the text in the question, which requests the reverse. So +1 from me on this answer. But then the OP said in comments that the map keys must match the list, a yet again different check. (Sigh.)

                        – Stuart Marks
                        yesterday













                        @StuartMarks well, if they must match, I’d use if(m.size() != ll.size() || !m.keySet().containsAll(ll)), as I suppose, m.keySet().containsAll(ll) is potentially faster than ll.containsAll(m.keySet())

                        – Holger
                        yesterday





                        @StuartMarks well, if they must match, I’d use if(m.size() != ll.size() || !m.keySet().containsAll(ll)), as I suppose, m.keySet().containsAll(ll) is potentially faster than ll.containsAll(m.keySet())

                        – Holger
                        yesterday













                        @Holger At the time this answer was written, it matched the code in the question. The OP subsequently changed the requirements.

                        – Stuart Marks
                        yesterday





                        @Holger At the time this answer was written, it matched the code in the question. The OP subsequently changed the requirements.

                        – Stuart Marks
                        yesterday











                        0














                        Here is another solution:



                            if (ll  .parallelStream()
                        .filter(v -> !m.containsKey(v)) // Filter alle values not contained in the map
                        .count() == 0) { // If no values are left then every key was present
                        // do something
                        } else {
                        throw new RuntimeException("hello");
                        }


                        Just wanted to show a different approach






                        share|improve this answer






























                          0














                          Here is another solution:



                              if (ll  .parallelStream()
                          .filter(v -> !m.containsKey(v)) // Filter alle values not contained in the map
                          .count() == 0) { // If no values are left then every key was present
                          // do something
                          } else {
                          throw new RuntimeException("hello");
                          }


                          Just wanted to show a different approach






                          share|improve this answer




























                            0












                            0








                            0







                            Here is another solution:



                                if (ll  .parallelStream()
                            .filter(v -> !m.containsKey(v)) // Filter alle values not contained in the map
                            .count() == 0) { // If no values are left then every key was present
                            // do something
                            } else {
                            throw new RuntimeException("hello");
                            }


                            Just wanted to show a different approach






                            share|improve this answer















                            Here is another solution:



                                if (ll  .parallelStream()
                            .filter(v -> !m.containsKey(v)) // Filter alle values not contained in the map
                            .count() == 0) { // If no values are left then every key was present
                            // do something
                            } else {
                            throw new RuntimeException("hello");
                            }


                            Just wanted to show a different approach







                            share|improve this answer














                            share|improve this answer



                            share|improve this answer








                            edited yesterday

























                            answered yesterday









                            user489872user489872

                            1,36031335




                            1,36031335






























                                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%2f54141672%2fcheck-the-keys-in-the-map-matching-with-the-list-content-in-java%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

                                Сан-Квентин

                                8-я гвардейская общевойсковая армия

                                Алькесар