Using removeif on a hashmap [duplicate] - java

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I am trying to remove entries from a Hashmap, if i have already used them. Sadly, I'm not familier with Java 8 lambda expressions, so I'm not sure how to remove the entries correctly. Could somebody help me or explain what I have to do?
Here is the way I've tried doing it:
ArrayList<Integer> range10 = new ArrayList<Integer>();
ArrayList<Integer> range15 = new ArrayList<Integer>();
ArrayList<Integer> rangeMax = new ArrayList<Integer>();
for (int age = 16; age <= 100; age++){
for (Entry<Integer, Partner> entry : dbMap.entrySet()){
int key = entry.getKey();
Partner person = entry.getValue();
if (person.getAge() == alter && person.getAgeRange() == 10){
range10.add(key);
entry.setValue(null);
}
else if (person.getAge() == alter && person.getAgeRange() == 15){
range15.add(key);
entry.setValue(null);
}
else if (person.getAge() == age){
rangeMax.add(key);
entry.setValue(null);
}
dbMap.entrySet().removeIf(entries->entries.getValue().equals(null));
}
And I get a java.lang.NullPointerException for it. I don't think this is a duplicate to asking what a NullPointerexception is, since I'm primarily asking how to use the removeif-function.

You get that because you call .equals() on getValue() object, which is null, so it will not work. That happens here:
dbMap.entrySet().removeIf(entries->entries.getValue().equals(null));
What you have to do is this:
dbMap.entrySet().removeIf(entries->entries.getValue() == null);

Related

Removing all elements from map that does not match leads to java.util.ConcurrentModificationException [duplicate]

This question already has answers here:
Why is a ConcurrentModificationException thrown and how to debug it
(8 answers)
Closed 2 years ago.
I wrote the following code:
for (Character currentChar : userDocuments.keySet()) {
List<QueryDocumentSnapshot> currentList = userDocuments.get(currentChar);
if (currentList == null) {
userDocuments.remove(currentChar);
continue;
}
for (int index = 0; index < currentList.size(); ++index) {
final String currentFullName = currentList.get(index).getString("full_name");
if (currentFullName == null || !(searchText.contains(currentFullName))) {
currentList.remove(index);
}
}
if (currentList.size() == 0) {
userDocuments.remove(currentChar);
}
}
I want to iterate over a map Map<Character,List<QueryDocumentSnapshot>> check if the full_name (field of each QueryDocumentSnapshot) contains searchText and if it's not, remove this element from the list. In case list is empty, remove the entire list. But for some reason I get java.util.ConcurrentModificationException on the first line. Also, how can I use contains without case sensitive?
The ConcurrentModificationException occurs when an object is tried to be modified concurrently when it is not permissible. This exception usually comes when one is working with Java Collection classes. For Example - It is not permissible for a thread to modify a Collection when some other thread is iterating over it.
In your case, it is arising coz you are trying to remove some elements from both the Map and ArrayList while iterating over them.
You can avoid it using:
Iterator<Map.Entry<Character, List<QueryDocumentSnapshot>>> mapIterator = userDocuments.entrySet().iterator();
while (mapIterator.hasNext())
{
Map.Entry<Character,List<QueryDocumentSnapshot>> entry = mapIterator.next();
List<QueryDocumentSnapshot> currentList = entry.getValue();
if (currentList == null) {
mapIterator.remove();
continue;
}
Iterator<QueryDocumentSnapshot> listIterator = currentList.iterator();
while (listIterator.hasNext()) {
final String currentFullName = listIterator.next().getString("full_name");
if (currentFullName == null || !(searchText.contains(currentFullName))){
listIterator.remove();
}
}
if (currentList.size() == 0) {
mapIterator.remove();
}
}
And to answer your question 'how can I use contains without case sensitive' , you can simply use something like this:
searchText.toLowerCase().contains(currentFullName.toLowerCase())

How can I dynamically populate a query with a List / Array of items in SQL WHERE IN [duplicate]

This question already has answers here:
PreparedStatement IN clause alternatives?
(33 answers)
Closed 3 years ago.
I have a List<Long> matchingLongs = new Arraylist(); that I would like to pass to an SQL statement :
WHERE Id IN (matchingLongs);
How can I dynamically populate the Longs into the query?
If I would print to console it should look like :
WHERE Id IN (1223, 9834, 3, 924, 88778, 65652165223, 34, 8723738793287);
Thank you all.
I think you should iterate matchingLongs, and then add each item to a new string.
private String getSqlArrayFromList(final List<Long> matchingLongs) {
StringBuilder sbuilder = new StringBuilder();
int index = 0;
for (Long matchingLong : matchingLongs) {
if (index == 0) {
sbuilder.append(matchingLong);
} else if (index > 0 && index < matchingLongs.size()) {
sbuilder.append(",").append(matchingLong);
}
index++;
}
return sbuilder.toString();
}
How about to change one string.
if (matchingLongs.isEmpty()) {
return;
}
String str = matchingLongs.toString().replaceAll("[", "(").replaceAll("]", ")");

What is the best way to create a List of "unique" objects in Java [duplicate]

This question already has answers here:
Remove duplicates from a list of objects based on property in Java 8 [duplicate]
(9 answers)
Closed 6 years ago.
I am trying to create a unique list. I can not use a "Set" because I need to assign some of the values as I iterate though it.
Right now I doing this to create a unique list. Does anyone know a better way?
List<Thing> things = previousThings.stream()
.collect(Collectors.toSet()).stream()
.collect(Collectors.toList());
I was thinking that if I convert it to a set and the back to a list it would eliminate any duplicate entries. I think it needs to be a list so that I can use "List.set(..)" to update according to what might already be in my repository.
for(int i = 0; i < things.size(); i++) {
if(things.get(i).id == null) {
existingThing = thingRepository.getByName(things.get(i).getName());
if(existingThing != null) {
things.set(i, existingThing);
} else {
things.set(i, thingRepository.save(things.get(i));
}
}
}
I thought before that I wouldn't be able to use the .distinct() because it uses .equals() which is based off of 'Thing.id' and some of the 'Things' don't have an 'id' yet. Then I realized that by the end of the forLoop everything is assigned an id by the repository.
List<Thing> things = previousThings;
for(int i = 0; i < things.size(); i++) {
if(things.get(i).id == null) {
existingThing = thingRepository.getByName(things.get(i).getName());
if(existingThing != null) {
things.set(i, existingThing);
} else {
things.set(i, thingRepository.save(things.get(i));
}
}
}
List<Thing> distinctThings = things.stream().distinct().collect(Collectors.toList);

Search for String in List [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
public Account findByInterest(String interest){
for(Map.Entry<Long, Account> e : accounts.entrySet()){
for(int i = 0; i < e.getValue().getInterests().size(); i++)
{
if(e.getValue().getInterests().get(i) == interest){
return e.getValue();
}
}
}
return null;
}
I'm trying to search in a HashTable of Objects to find an objected with a List of Strings, which has the same string as this method receives... What am I doing wrong?
To compare string values use the equals method.
Change
if(e.getValue().getInterests().get(i) == interest){
to
if(e.getValue().getInterests().get(i).equals(interest)){

How to remove object from arraylist [duplicate]

This question already has answers here:
Java, Using Iterator to search an ArrayList and delete matching objects
(1 answer)
How do I compare strings in Java?
(23 answers)
Closed 10 years ago.
I have class with ArrayList of teams and i want remove team which name is "FREE";
so i tried:
public void removeFree()
{
for (int i = 0 ; i < numberOfTeams ; i++ )
{
if (this.getListOfTeams().get(i).getName() == "FREE")
{
this.getListOfTeams().remove(i);
}
else
{}
}
}
That makes my app crash.
Use, equals() method to check if two strings are meaningfully equal. == operator just checks if two reference variables refer to the same object.
if (this.getListOfTeams().get(i).getName() == "FREE")
should be
if (this.getListOfTeams().get(i).getName().equals("FREE"))
Also to add more, even if you use equals() you'd get ConcurrentModificationException as you are removing the elements from the arrayList while iterating over it. you have to use an iterator and remove elements from it rather.
Iterator<Team> itr = getListOfTeams.iterator();
while(itr.hasNext()){
if (itr.next().getName().equals("FREE"))
{
itr.remove();
}
else
{}
}
}
To remove an element from a List while iterating it, it's safer to use an Iterator along with the remove method:
for (Iterator it = getListOfTeams().iterator;it.hasNext();) {
String name = it.next();
if ("FREE".equals(name) {
it.remove();
}
else{}
}
Please note how String value comparison in Java should usually be done by means of the String.equals() method. == is the reference equality operator. See How do I compare strings in Java?
You are trying to remove an item while you are looping the same ArrayList. You need to clone first, iterate the cloned list and then delete the items of the first pointer.
so consider this:
List<Object> arrayToIterate = getListOfTeams().clone();
for (int i = 0 ; i < numberOfTeams ; i++ )
{
if (tarrayToIterate.get(i).getName().equals("FREE"))
{
this.getListOfTeams().remove(i);
}
else
{}
}
Also you are comparing an string with == instead of equals.

Categories