Search for String in List [duplicate] - java

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)){

Related

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

Using removeif on a hashmap [duplicate]

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

Nullpointerexception when I perform depth first search [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
Suppose area1 has three contents 2,3,4, area2 has three contents 1,2,3 and area3 has two contents 1,2. m is the map that keys are locationid and values are list of contentid. For example, area1 has the map (1,{2,3,4}). Each area choose 1 content and find all the combination. I use dfs (recursion) to solve this problem but there is a nullpointerexception in line1. The intermediate is a list of string and i iterate through the list and their types are both string, why there is a null pointer exception? This is a specific condition in nullpointerexception and it is not duplicate.
public static List<String> dfs(String digits,Map<String, List<String>> m) {
List<String> result = new ArrayList<String>();
if(digits.length() == 0){
return result;
}
if(digits.length() == 1){
return m.get(digits.charAt(0));
}
List<String> intermediate = dfs(digits.substring(1, digits.length()),m);
for(String first : m.get(Character.toString(digits.charAt(0)))){
for(String rest : intermediate){ // line1
result.add(first + rest);
}
}
return result;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
String digits="123";
Map<String,List<String>> selected=new HashMap<>();
selected.put("1", new ArrayList<>(Arrays.asList("4","2","3")));
selected.put("2", new ArrayList<>(Arrays.asList("1","2","3")));
selected.put("3", new ArrayList<>(Arrays.asList("1","2")));
dfs(digits,selected);
}
I guess the problem is here:
return m.get(digits.charAt(0));
it should return null, since digits.charAt(0) is not a String
you need to use substring or Character.toString( here to extract the number

Add String Values from a for loop to list [duplicate]

This question already has answers here:
How to make a new List in Java
(25 answers)
Closed 7 years ago.
public static void printFiles(NodeList node) {
for (int i = 0; i < node.getLength(); i++) {
Node file = node.item(i);
String nodeValue = file.getAttributes().getNamedItem("urlName").getNodeValue();
System.out.println(nodeValue);
}
}
output:
0a4f171c-e0a4-4aa8-b43b-3989c235ff58.txt
0ccfa1a4-16b0-4e1f-abc9-e17907bb591f.txt
17c0545b-377e-4e0a-bb45-29f38fc91533.txt
3b341bf0-2cd7-46fe-a834-5b67804e5ff1.txt
48121209-d58e-4565-83b7-05062799be6e.txt
511b7a89-e4de-4f6e-9c8f-5ba65f675d7b.txt
compress.txt
dadadada.txt
e0c44cb9-2b1c-444c-a429-64531ea6a9a0.txt
e68b1d1d-9a66-4678-a6c1-76c64ae8be08.txt
hgafgahfka.txt
jdjajhdajdajd.txt
test1.txt
test2.txt
I parsed the xml document and got the values through for loop but those alues need to be in single place like List so that I can pass to some other function.can some one please let me know how to add those in a List .Below is the code and the current Output.
String input = "hello world";
List<String> list = new ArrayList<>();
list.add(input);
System.out.println(list.get(0));
> hello world
Good luck

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