Check the keys in the map matching with the List content in Java
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
add a comment |
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
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
Jan 11 at 7:02
How about thisll.stream().filter(s -> !m.containsKey(s)).forEach(s -> { throw new RuntimeException("Not found"); });
?
– manfromnowhere
Jan 11 at 7:06
@Sweeper Sorry , I will modify the question. Technically, the contents in the list and keys in the map should match.
– sparker
2 days ago
2
If they really need to match, then test something likem.keySet().equals(new HashSet<>(ll))
. Or maybe keep the required keys in a set in the first place.
– Stuart Marks
2 days ago
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
2 days ago
add a comment |
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
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
java lambda java-8 java-stream
edited 2 days ago
sparker
asked Jan 11 at 6:53
sparkersparker
331414
331414
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
Jan 11 at 7:02
How about thisll.stream().filter(s -> !m.containsKey(s)).forEach(s -> { throw new RuntimeException("Not found"); });
?
– manfromnowhere
Jan 11 at 7:06
@Sweeper Sorry , I will modify the question. Technically, the contents in the list and keys in the map should match.
– sparker
2 days ago
2
If they really need to match, then test something likem.keySet().equals(new HashSet<>(ll))
. Or maybe keep the required keys in a set in the first place.
– Stuart Marks
2 days ago
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
2 days ago
add a comment |
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
Jan 11 at 7:02
How about thisll.stream().filter(s -> !m.containsKey(s)).forEach(s -> { throw new RuntimeException("Not found"); });
?
– manfromnowhere
Jan 11 at 7:06
@Sweeper Sorry , I will modify the question. Technically, the contents in the list and keys in the map should match.
– sparker
2 days ago
2
If they really need to match, then test something likem.keySet().equals(new HashSet<>(ll))
. Or maybe keep the required keys in a set in the first place.
– Stuart Marks
2 days ago
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
2 days ago
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
Jan 11 at 7:02
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
Jan 11 at 7:02
How about this
ll.stream().filter(s -> !m.containsKey(s)).forEach(s -> { throw new RuntimeException("Not found"); });
?– manfromnowhere
Jan 11 at 7:06
How about this
ll.stream().filter(s -> !m.containsKey(s)).forEach(s -> { throw new RuntimeException("Not found"); });
?– manfromnowhere
Jan 11 at 7:06
@Sweeper Sorry , I will modify the question. Technically, the contents in the list and keys in the map should match.
– sparker
2 days ago
@Sweeper Sorry , I will modify the question. Technically, the contents in the list and keys in the map should match.
– sparker
2 days ago
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
2 days ago
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
2 days ago
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
2 days ago
@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
2 days ago
add a comment |
6 Answers
6
active
oldest
votes
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("");
}
1
Orif(! map.keySet().stream().allMatch(list::contains))
, but of course,if(!list.containsAll(map.keySet()))
is the canonical solution.
– Holger
2 days ago
add a comment |
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!");
}
add a comment |
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");
}
1
I think OP is looking for an answer wrt to java-8 (something using streams and filters) here.
– Nicholas K
2 days ago
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
2 days ago
1
Ummm...if (...m.keySet() == null ...)
... what is that? ThekeySet
can never benull
, and in any case: the comparison of thesize()
and thecontainsAll
call boil down to a simpleif (Objects.equals(m.keySet(), set))
...
– Marco13
2 days ago
@MarcoPolo Thanks for the feedback, answer updated.
– Tim Biegeleisen
2 days ago
add a comment |
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);
}
add a comment |
You can simply change your existing code to -
if(!m.keySet().containsAll(ll)) {
System.out.println("Throws Exception");
}
This will solve your problem. :)
2
This logic has a problem. Should the hashmap's keyset contain extra items, your code would still return true. Also, ifnull
on both sides of the comparison means equal, then you would have to cover that case as well.
– Tim Biegeleisen
Jan 11 at 7:03
@p.bansal - The same check performed in reverse was what OP is mostly trying to look forward to.
– nullpointer
2 days ago
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
2 days ago
@StuartMarks well, if they must match, I’d useif(m.size() != ll.size() || !m.keySet().containsAll(ll))
, as I suppose,m.keySet().containsAll(ll)
is potentially faster thanll.containsAll(m.keySet())
…
– Holger
2 days ago
@Holger At the time this answer was written, it matched the code in the question. The OP subsequently changed the requirements.
– Stuart Marks
2 days ago
|
show 1 more comment
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
add a comment |
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
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
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("");
}
1
Orif(! map.keySet().stream().allMatch(list::contains))
, but of course,if(!list.containsAll(map.keySet()))
is the canonical solution.
– Holger
2 days ago
add a comment |
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("");
}
1
Orif(! map.keySet().stream().allMatch(list::contains))
, but of course,if(!list.containsAll(map.keySet()))
is the canonical solution.
– Holger
2 days ago
add a comment |
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("");
}
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("");
}
edited 2 days ago
answered 2 days ago
nullpointernullpointer
45.1k1096184
45.1k1096184
1
Orif(! map.keySet().stream().allMatch(list::contains))
, but of course,if(!list.containsAll(map.keySet()))
is the canonical solution.
– Holger
2 days ago
add a comment |
1
Orif(! map.keySet().stream().allMatch(list::contains))
, but of course,if(!list.containsAll(map.keySet()))
is the canonical solution.
– Holger
2 days ago
1
1
Or
if(! map.keySet().stream().allMatch(list::contains))
, but of course, if(!list.containsAll(map.keySet()))
is the canonical solution.– Holger
2 days ago
Or
if(! map.keySet().stream().allMatch(list::contains))
, but of course, if(!list.containsAll(map.keySet()))
is the canonical solution.– Holger
2 days ago
add a comment |
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!");
}
add a comment |
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!");
}
add a comment |
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!");
}
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!");
}
answered 2 days ago
ETOETO
2,163423
2,163423
add a comment |
add a comment |
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");
}
1
I think OP is looking for an answer wrt to java-8 (something using streams and filters) here.
– Nicholas K
2 days ago
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
2 days ago
1
Ummm...if (...m.keySet() == null ...)
... what is that? ThekeySet
can never benull
, and in any case: the comparison of thesize()
and thecontainsAll
call boil down to a simpleif (Objects.equals(m.keySet(), set))
...
– Marco13
2 days ago
@MarcoPolo Thanks for the feedback, answer updated.
– Tim Biegeleisen
2 days ago
add a comment |
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");
}
1
I think OP is looking for an answer wrt to java-8 (something using streams and filters) here.
– Nicholas K
2 days ago
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
2 days ago
1
Ummm...if (...m.keySet() == null ...)
... what is that? ThekeySet
can never benull
, and in any case: the comparison of thesize()
and thecontainsAll
call boil down to a simpleif (Objects.equals(m.keySet(), set))
...
– Marco13
2 days ago
@MarcoPolo Thanks for the feedback, answer updated.
– Tim Biegeleisen
2 days ago
add a comment |
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");
}
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");
}
edited 2 days ago
answered Jan 11 at 7:02
Tim BiegeleisenTim Biegeleisen
220k1388141
220k1388141
1
I think OP is looking for an answer wrt to java-8 (something using streams and filters) here.
– Nicholas K
2 days ago
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
2 days ago
1
Ummm...if (...m.keySet() == null ...)
... what is that? ThekeySet
can never benull
, and in any case: the comparison of thesize()
and thecontainsAll
call boil down to a simpleif (Objects.equals(m.keySet(), set))
...
– Marco13
2 days ago
@MarcoPolo Thanks for the feedback, answer updated.
– Tim Biegeleisen
2 days ago
add a comment |
1
I think OP is looking for an answer wrt to java-8 (something using streams and filters) here.
– Nicholas K
2 days ago
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
2 days ago
1
Ummm...if (...m.keySet() == null ...)
... what is that? ThekeySet
can never benull
, and in any case: the comparison of thesize()
and thecontainsAll
call boil down to a simpleif (Objects.equals(m.keySet(), set))
...
– Marco13
2 days ago
@MarcoPolo Thanks for the feedback, answer updated.
– Tim Biegeleisen
2 days ago
1
1
I think OP is looking for an answer wrt to java-8 (something using streams and filters) here.
– Nicholas K
2 days ago
I think OP is looking for an answer wrt to java-8 (something using streams and filters) here.
– Nicholas K
2 days ago
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
2 days ago
@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
2 days ago
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
2 days ago
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
2 days ago
@MarcoPolo Thanks for the feedback, answer updated.
– Tim Biegeleisen
2 days ago
@MarcoPolo Thanks for the feedback, answer updated.
– Tim Biegeleisen
2 days ago
add a comment |
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);
}
add a comment |
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);
}
add a comment |
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);
}
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);
}
edited 2 days ago
answered Jan 11 at 7:03
Nicholas KNicholas K
6,21051031
6,21051031
add a comment |
add a comment |
You can simply change your existing code to -
if(!m.keySet().containsAll(ll)) {
System.out.println("Throws Exception");
}
This will solve your problem. :)
2
This logic has a problem. Should the hashmap's keyset contain extra items, your code would still return true. Also, ifnull
on both sides of the comparison means equal, then you would have to cover that case as well.
– Tim Biegeleisen
Jan 11 at 7:03
@p.bansal - The same check performed in reverse was what OP is mostly trying to look forward to.
– nullpointer
2 days ago
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
2 days ago
@StuartMarks well, if they must match, I’d useif(m.size() != ll.size() || !m.keySet().containsAll(ll))
, as I suppose,m.keySet().containsAll(ll)
is potentially faster thanll.containsAll(m.keySet())
…
– Holger
2 days ago
@Holger At the time this answer was written, it matched the code in the question. The OP subsequently changed the requirements.
– Stuart Marks
2 days ago
|
show 1 more comment
You can simply change your existing code to -
if(!m.keySet().containsAll(ll)) {
System.out.println("Throws Exception");
}
This will solve your problem. :)
2
This logic has a problem. Should the hashmap's keyset contain extra items, your code would still return true. Also, ifnull
on both sides of the comparison means equal, then you would have to cover that case as well.
– Tim Biegeleisen
Jan 11 at 7:03
@p.bansal - The same check performed in reverse was what OP is mostly trying to look forward to.
– nullpointer
2 days ago
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
2 days ago
@StuartMarks well, if they must match, I’d useif(m.size() != ll.size() || !m.keySet().containsAll(ll))
, as I suppose,m.keySet().containsAll(ll)
is potentially faster thanll.containsAll(m.keySet())
…
– Holger
2 days ago
@Holger At the time this answer was written, it matched the code in the question. The OP subsequently changed the requirements.
– Stuart Marks
2 days ago
|
show 1 more comment
You can simply change your existing code to -
if(!m.keySet().containsAll(ll)) {
System.out.println("Throws Exception");
}
This will solve your problem. :)
You can simply change your existing code to -
if(!m.keySet().containsAll(ll)) {
System.out.println("Throws Exception");
}
This will solve your problem. :)
edited 2 days ago
nullpointer
45.1k1096184
45.1k1096184
answered Jan 11 at 6:59
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, ifnull
on both sides of the comparison means equal, then you would have to cover that case as well.
– Tim Biegeleisen
Jan 11 at 7:03
@p.bansal - The same check performed in reverse was what OP is mostly trying to look forward to.
– nullpointer
2 days ago
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
2 days ago
@StuartMarks well, if they must match, I’d useif(m.size() != ll.size() || !m.keySet().containsAll(ll))
, as I suppose,m.keySet().containsAll(ll)
is potentially faster thanll.containsAll(m.keySet())
…
– Holger
2 days ago
@Holger At the time this answer was written, it matched the code in the question. The OP subsequently changed the requirements.
– Stuart Marks
2 days ago
|
show 1 more comment
2
This logic has a problem. Should the hashmap's keyset contain extra items, your code would still return true. Also, ifnull
on both sides of the comparison means equal, then you would have to cover that case as well.
– Tim Biegeleisen
Jan 11 at 7:03
@p.bansal - The same check performed in reverse was what OP is mostly trying to look forward to.
– nullpointer
2 days ago
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
2 days ago
@StuartMarks well, if they must match, I’d useif(m.size() != ll.size() || !m.keySet().containsAll(ll))
, as I suppose,m.keySet().containsAll(ll)
is potentially faster thanll.containsAll(m.keySet())
…
– Holger
2 days ago
@Holger At the time this answer was written, it matched the code in the question. The OP subsequently changed the requirements.
– Stuart Marks
2 days ago
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
Jan 11 at 7:03
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
Jan 11 at 7:03
@p.bansal - The same check performed in reverse was what OP is mostly trying to look forward to.
– nullpointer
2 days ago
@p.bansal - The same check performed in reverse was what OP is mostly trying to look forward to.
– nullpointer
2 days ago
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
2 days ago
@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
2 days ago
@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
2 days ago
@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
2 days ago
@Holger At the time this answer was written, it matched the code in the question. The OP subsequently changed the requirements.
– Stuart Marks
2 days ago
@Holger At the time this answer was written, it matched the code in the question. The OP subsequently changed the requirements.
– Stuart Marks
2 days ago
|
show 1 more comment
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
add a comment |
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
add a comment |
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
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
edited 2 days ago
answered 2 days ago
user489872user489872
1,36031335
1,36031335
add a comment |
add a comment |
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.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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
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
Jan 11 at 7:02
How about this
ll.stream().filter(s -> !m.containsKey(s)).forEach(s -> { throw new RuntimeException("Not found"); });
?– manfromnowhere
Jan 11 at 7:06
@Sweeper Sorry , I will modify the question. Technically, the contents in the list and keys in the map should match.
– sparker
2 days ago
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
2 days ago
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
2 days ago