enter image description hereI have a hashmap which I need to compare values of the String array to certain strings and remove those which are equal. In this instance I know the String [] at a certain index = "RES", but when I iterate through the if (equality) statement returns false each time. Do I have to worry about overriding .equals() when simply extending hashmap? What is wrong with the if statement?
public void filter(){
Iterator<Map.Entry<String, String[]>> iter = this.entrySet().iterator();
while(iter.hasNext()){
Map.Entry<String,String[]> entry = iter.next();
String[] current = entry.getValue();
if(current[0].trim().equalsIgnoreCase("RES")){
this.remove(entry.getKey());
}
}
}
Replace:
this.remove(entry.getKey());
With:
iter.remove();
Related
I have an ArrayList with a set of (same) string values which I need to compare with a single String value and return true or false. Is there any way to do
that in Java?
For example, say I have a <String>ArrayList with 5 values = foo, foo, foo, foo, foo (My requirement is such that all the values in the arraylist will be the SAME) and I have a String str = "foo". I need to verify that whether ALL the values in the arraylist is the SAME as the string value i.e., all the values present in the arraylist SHOULD be "foo".
I tried to google this info and all I can see is suggestions to use contains() method, in different ways, which will return true even if anyone value in the arraylist contains the specified value.
I even figured a workaround for this - Creating another arraylist with expected values and compare the two lists using equals() method and it seems
to be working. I was just wondering whether there is any simple way to achieve this.
That's simple with Java 8:
String str = "foo";
List<String> strings = Arrays.asList("foo", "foo", "foo", "foo", "foo");
boolean allMatch = strings.stream().allMatch(s -> s.equals(str));
For Java 7 replace the last line with:
boolean allMatch = true;
for (String string : strings) {
if (!string.equals(str)) {
allMatch = false;
break;
}
}
If you want to know if the array contains the string use ArrayList::contains()
String s = "HI";
ArrayList<String> strings = // here you have your string
if (string.contains(s)) {
// do your stuff
}
If you want to check if all values are same, iterate and count. If you have JAVA8 check steffen sollution.
boolean areSame = true;
for (String str : strings) {
if (!str.equals(s)) areSame = false;
}
if (areSame) {
// all elements are same
}
1) You can the pass the arraylist into a set.
2) Now you can get the size of set, if it is equal to 1 that means all elements are same.
3) Now you can use the contains on set to check if your value is present in it or not.
public static void main(String[] args){
String toBeCompared="foo";
List<String> list=new ArrayList<String>();
list.add("foo");
list.add("foo");
list.add("foo");
list.add("foo");
list.add("foo");
Set<String> set=new HashSet<String>(list);
if(1==set.size()){
System.out.println(set.contains(toBeCompared));
}
else{
System.out.println("List has different values");
}
}
You can use this method to do that
private boolean allAreSame(ArrayList<String> stringList, String compareTo){
for(String s:stringList){
if(!s.equals(compareTo))
return false;
}
return true;
}
I would do it like this:
ArrayList<String> foos = new ArrayList<>();
String str = "foo";
for (String string : foos) {
if(string.equals(str)){
System.out.println("True");
}
}
can somebody please tell me if this is the right way to convert an object to string? Firstly the error below
public String generateResponse(HashSet<String> words){
Iterator it = words.iterator();
while(it.hasNext()){
String word = it.next(); // Object to string error
String input = responseMap.get(word);
if(input != null){
return input;
}
}
return pickDefaultResponse();
}
Then i did this, and it worked.
public String generateResponse(HashSet<String> words){
Iterator it = words.iterator();
while(it.hasNext()){
String input = responseMap.get(it.next());// i put it here
if(input != null){
return input;
}
}
return pickDefaultResponse();
}
I was so curious about the error. I made a little research, since i'm just learning i don't know if this is right or wrong. it worked, but is it right?
public String generateResponse(HashSet<String> words){
Iterator it = words.iterator();
while(it.hasNext()){
String word = it.next().toString();// added toString()
String input = responseMap.get(word);
if(input != null){
return input;
}
}
return pickDefaultResponse();
}
Iterator it = words.iterator();
This statement ignores the type parameter of the iterator. That means the return type of it.next() is Object, which can't be assigned to String without a cast.
responseMap.get(it.next());
works, because the parameter of Map.get has the type Object.
String word = it.next().toString();
Will work too, since the Object returned by it.next() actually is a String and therefore toString returns the same String.
This would work too:
String word = (String) (it.next());
But I recommend adding a type parameter to the Iterator variable:
Iterator<String> it = words.iterator();
while(it.hasNext()){
String word = it.next();
// ...
Note: "Ignoring" a type parameter is a bad idea most times.
String word = it.next()
firstly it does not have a " ; " to end the string, and secondly you need to explicitly cast it to String
change the code to String word = (String)it.next();
change raw type iterator to generic type.
Iterator it = words.iterator();
to
Iterator<String> it = words.iterator();
Yup it is
You cant assign a hashset directly to a string.
You have to convert it. using the toString method
As much to my info, in ur second case...
when you use the below code
"String input = responseMap.get(it.next());"
There are many overloaded methods for different datatypes. So when u provided a hashset directly. It worked correctly
So I have a hashmap which contains key as Strings and value as Integers of the count of those strings occurring in my Set
for eg I would have a hashMap as follows
Key Value
abcd 4 (meaning there are 4 duplicate strings of abcd in my Set defined someplace)
----- 13
b-b- 7
and so on..
Now what I am trying to do is remove all the empty strings entries from my HashMap. So in the above example I would want to remove all the empty strings with value 13. So my resulting HashMap would be
Key Value
abcd 4
b-b- 7
This is my code that tries to do the same. generateFeedbackMap() is function which returns the HashMap in consideration StringIterator is a class which I have defined which iterates over through each character of my Strings.
for(String key : generateFeedbackMap().keySet()) {
StringIterator it = new StringIterator(key);
int counter = 0;
while(it.hasNext()){
String nextChar = it.next();
if(nextChar.equals("-")){
counter++;
}
Iterator<Map.Entry<String, Integer>> mapIterator = generateFeedbackMap().entrySet().iterator();
if(counter >= key.length()){
while(mapIterator.hasNext()){
Map.Entry<String, Integer> entry = mapIterator.next();
if(entry.getKey().equals(key)){
mapIterator.remove();
}
}
}
}
}
So I increment the counter wherever I find a "-" character. When the counter equals my key string length which means it is an empty string, I remove it using Map Iterator but this does not remove the entry from my Map. What am I doing wrong?
generateFeedbackMap() makes it sound like you’re getting a copy of the underlying map, in which case removing a key from the copy won’t affect the underlying map. If you’re actually getting the map, then you should rename your method.
Regardless, the following would accomplish the same as your original code (but will only remove from the copy).
Map<String,Integer> feedbackMap = generateFeedbackMap();
for ( String key : feedbackMap.keySet() ) {
if ( key.matches("-+") ) {
feedbackMap.remove(key);
}
}
If you’re stuck getting a copy of the underlying map, then you do need to create your new helpfulMap. But you can still use a regular expression and other Map functions to speed things up:
Map<String,Integer> helpfulMap = new HashMap<>();
for ( Map.Entry<String,Integer> entry : generateFeedbackMap().entrySet() ) {
if ( ! entry.getKey().matches("-+") ) {
helpfulMap.put(entry.getKey(),entry.getValue());
}
}
Okay guys, I think I figured out a solution. I just copied all my current entries from oldMap to a new defined HashMap which would contain at least one letter in their keys. So essentially I got rid of all the removing and iterating over strings and just use another HashMap instead as below
Map<String, Integer> HelpfulMap = new HashMap<String,Integer>();
for(String key : generateFeedbackMap().keySet()) {
StringIterator it = new StringIterator(key);
while(it.hasNext()){
String nextChar = it.next();
if(!nextChar.equals("-")){
HelpfulMap.put(key, generateFeedbackMap().get(key));
}
}
}
I don't know what I was doing previously. I went for a good shower and came up with this idea and it worked. I love programming!
Thanks everyone for your inputs!
I have a TreeSet filled with Strings that I want to use to see if any of the keys inside it start with a string outside the set, and be able to get that specific key and do something with it (put it in a string) For example my String is test 1 2 3 and I have a key in the set that is test 1 2 which should return true and tell me the key. The reason I am using a TreeSet is because I need a case-insensitive way to read the keys in my yaml file. I have used an iterator on the set before using
Iterator<String> itr = myTreeSet.iterator();
while(itr.hasNext())
if (myString.startsWith(itr.next())){ }
but I could not the key that made the if statement true.
You're really close... it's this line that is wrong
if (myString.startsWith(itr.next())){ }
it should be this - because the key should start with the myString.
String theKey = null;
while(itr.hasNext()) {
theKey = itr.next();
if (theKey.startsWith(myString)) {
return theKey;
}
}
return null;
Call subSet() is more proper way for tree set than iterating over it.
myTreeSet.subSet(str, str + "\uffff")
I am not sure to get what you want:
Iterator<String> itr = myTreeSet.iterator();
while(itr.hasNext()) {
String myString = itr.next()
if (myString.startsWith(myString)){
System.out.println(myString);
}
}
I have an hashmap declared as
private HashMap testMessages = null;
I will be storing string values in both key and value part of the hashmap retrieved from oracle table.
I am not concerned about the hashmap keys. I want to retrieve the hashmap values alone and check whether string variable filename is prefixed with one of the hash map value and return true if it's same. I want to ensure that hash map values are not null and empty.
function (string filename)
{..
loop thru hashmap values
check whether the variable file name is prefixed with one of the hashmap values if so
return true
otherwise
return false
}
hashmap example:
key1,prod
key2,test
key3,dummy
filename example:
test123_20012010.csv
should return true since the file name is prefixed with one of the hashmap values
How can i do it?
for (String prefix : map.values()) {
if (filename.startsWith(prefix)) {
return true;
}
}
return false;
It should be noted that this is linear time in the number of entries in the map in the worst case. If you have multiple filename that you want to do the check for, it's much better to preprocess the prefixes and build something like a patricia trie and other fast dictionary-like data structures.
Here's a brute force approach to iterate over the hash map values and check whether filename begins with the value.
// generics version
private HashMap<String, String> testMessages = buildMap();
for (String v : testMessages.values()) {
if (filename.startsWith(v) {
// found a map value that starts the file name
}
}
// alternative non-generics version
private HashMap testMessages; // assigned somewhere
for (Object v : testMessages.values()) {
if (filename.startsWith((String) v) {
// found a map value that starts the file name
}
}
leeched from leepoint.net
public static void iterate_over_hashmap(Map mp) {
Iterator it = mp.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry)it.next();
System.out.println(pairs.getKey() + " = " + pairs.getValue());
}
}
You have to treat each entry as a key/value pair and iterate over those as a single entity. Then you cast it into Map.Entry and then you can read both separately
function(String fileName)
{
for(String value : hashMap.values())
{
if(fileName.startsWith(value))
return true;
}
return false;
}