Check if keys in TreeSet start with String, and get that key - java

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);
}
}

Related

Remove a value from a List nested in a Map

I've got a HashMap which contains an ArrayList as value. I want to check if one of the lists contains an object and remove that object from the list. How can I achieve that?
I've tried using some for loops, but then I get a ConcurrentModificationException. I can't get that exception away.
My hashmap:
Map<String,List<UUID>> inAreaMap = new HashMap<String, ArrayList<UUID>>();
I intend to check if the ArrayList contains the UUID I've got, and if so, I want to remove it from that ArrayList. But I don't know the String at that position of the code.
What I already tried:
for (List<UUID> uuidlist : inAreaMap.values()) {
for (UUID uuid : uuidlist) {
if (uuid.equals(e.getPlayer().getUniqueId())) {
for (String row : inAreaMap.keySet()) {
if (inAreaMap.get(row).equals(uuidlist)) {
inAreaMap.get(row).remove(uuid);
}
}
}
}
}
There is a more elegant way to do this, using Java 8:
Map<String, ArrayList<UUID>> map = ...
UUID testId = ...
// defined elsewhere
// iterate through the set of elements in the map, produce a string and list for each
map.forEach((string, list) -> {
// as the name suggests, removes if the UUID equals the test UUID
list.removeIf(uuid -> uuid.equals(testId));
});
try with the iterator.
inareamap.iterator().. and.. iterator.remove()
If you have Java 8, the solution of camaron1024's solution is the best. Otherwise you can make use of the fact that you have a list and iterate through it backwards by index.
for(ArrayList<UUID> uuidlist : inareamap.values()) {
for(int i=uuidlist.size()-1;i>=0;i--) {
if (uuidlist.get(i).equals(e.getPlayer().getUniqueId()))
uuidlist.remove(i);
}
}
Here the easy solution.
UUID key = ... ;
for(Map.Entry<String,ArrayList<UUID>> e : hm.entrySet()){
Iterator<UUID> itr = e.getValue().iterator();
while(itr.hasNext()){
if(itr.next() == key)
itr.remove();
}
}

How can I remove Strings from an ArrayList which contain only whitespace characters?

I want to remove all strings in a list which contain only whitespace characters. I tried the following code, but some lines were not removed:
List<String> getarray = /* ... */;
for (int i = 0; i < getarray.size(); i++) {
if (getarray.contains(" ").getarray.contains(null)) {
getarray.remove(i);
} else {
System.out.println("a: " + getarray.get(i));
}
}
This does only work for certain inputs, can somebody help me understand why?
Here is a list of inputs which did not work as intended
First of all use some Iterator to iterate and perform your operation of removing elements from ArrayList.
Second to solve your problem of empty string , you could use trim() and isEmpty() methods
try below code:
Iterator<String> it = getarray.iterator();
while (it.hasNext()) {
String myValue = it.next();
if (myValue.trim().isEmpty()) {
it.remove();
} else {
System.out.println("a: " + myValue);
}
}
Use Iterators if you want to remove elements. According to Java docs:
Iterator takes the place of Enumeration in the Java Collections Framework. Iterators differ from enumerations in two ways:
Iterators allow the caller to remove elements from the underlying collection during the iteration with well-defined semantics.
Method names have been improved
Try the following code:
Iterator<String> itr = getarray.iterator();
while (itr.hasNext()) {
String value = itr.next();
if (value.trim().isEmpty()) {
itr.remove();
} else {
System.out.println("a: " + value);
}
}
You misunderstand between element is empty or only composed of spaces AND element contain spaces :
So it's element.trim().isEmpty() instead of element.contains(" ");
.trim() removes spaces at start and at the ens of the String
So this will do your stuff, it will iterate over the list, and only keep the element which are not empty (or only compsed of spaces)
getarray = getarray.stream().filter(s -> !s.trim().isEmpty()).collect(Collectors.toList());
If you wan to print all after just do : getarray.forEach(System.out::println);

.Equals() not working while iterating hashmap

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();

Performing Loop Unrolling while iterating the hashmap

I am looking at a possibility of unrolling the loop which is written to iterate the elements in a hash map.Below posted is the code.
for (final Object key : map.keySet())
{
if (input_map.containsKey(key))
{
System.out.println("Matching key: " + key);
if (map.get(key).equals(input_map.get(key)))
{
System.out.println("hii!done");
}
else
{
System.out.println(key);
final String values =
key.
toString().
substring(key.toString().lastIndexOf("\\") + 1);
System.out.println("input_map" +
input_map.get(key));
System.out.println("map" + map.get(key));
}
}
}
Explanation:
Currently, comparison in the loop is being done based on one element at a time i.e "key".I am looking at a possibility where i can retrieve the next successive keys in one single iteration i.e(key,key+1,key+2).
Any Suggestions would be highly helpful.
Use the KeySet or EntrySet iterator() method and while loop through with hasNext() and next(). You need to handle cases where it has not 3 repeating elements. Then you have the 3 keys and should be able to easily access the values in the Map.
Iterator<Integer> it = myMap.keySet().iterator();
while(it.hasNext())
{
int first = it.next();
int second = it.next();
int third = it.next();
}

removing entries from a HashMap in Java

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!

Categories