Home > Blockchain >  List contains doesn't work with extra characters
List contains doesn't work with extra characters

Time:11-21

If you look at the example below, the first statement is true, although technically, the others should be too, they do contain "Halle 1".

The value that I'm comparing would be "Halle 1, Nebengebäude" or "Vor Halle 1", how could I make it so it works that way? It ignores everything, it just checks if any Item of the list contains "Halle 1". For example, in short so that all of the statements are true not just the first one.

import java.util.LinkedList;

public class Main {
    public static void main(String[] args) {
        LinkedList<String> analyzeTypeList = new LinkedList<>();

        analyzeTypeList.add("Halle 1");

        System.out.println(analyzeTypeList.contains("Halle 1"));
        System.out.println(analyzeTypeList.contains("Halle 1, Außerhalb"));
        System.out.println(analyzeTypeList.contains("Vor Halle 1"));
    }
}

I have those 2 lists below, the first one would be all the possible choices, while the second one is the actual data. How could I do it so that if the data has one of those values, let's say the data is "Halle 4, Außerhalb", so I want the statement to be true, because it contains Halle 4. The problem is because it also contains something else, "Außerhalb" the contains statement is false. How would I go about ignoring that "Außerhalb". Same thing goes when there's something in front - "Vor Halle 4"

true if contains one of those

Außerhalb
Halle 1
Halle 2
Halle 3
Halle 4
Halle 5
Halle 6
Halle 7
Halle 8
Halle 9
Halle 10
Halle 11
Halle 12
Halle 13
Gebäude 14

My data

Vor Halle 4
Halle 1, Montage
Halle 13, Lager
Halle 13, CNC-Maschine
Halle 13
Vor Halle 1, Parkplatz
Halle 13
Halle 4
Halle 7
Halle 7
Halle 2
Halle 7
Halle 13
Außerhalb
Halle 3
Halle 13
Halle 2
Halle 3
Halle 2
Außerhalb
Halle 10
Halle 7
Gebäude 14
Halle 2
Außerhalb
Halle 4
Halle 13
Außerhalb
Halle 13
Halle 3
Halle 4

This is how it looks in my code, whereas analyzeTypeList is the first List and ac.get(databaseName) returns one of the values from the second list:

for (DetailedAccident ac : detailedAccidentData)
    if (analyzeTypeList.contains(ac.get(databaseName)))
        count[analyzeTypeList.indexOf(ac.get(databaseName))]  = 1;

CodePudding user response:

You're using the wrong method for the job... Java's List contains method checks if the exact string exists within the list, see from the documentation:

Returns true if this list contains the specified element.

If you want to check for a none-specific pattern you can for example use Regex:

public class Test {

    private static final Pattern pattern = Pattern.compile(".*Halle.*");

    void findPattern(List<String> values) {
        for (String v : values) {
            if (pattern.matcher(v).matches()) {
                System.out.println(v);
            }
        }
    }

}
  •  Tags:  
  • java
  • Related