Home > front end >  Is there a way in java to check if a string is a part from many strings in a list
Is there a way in java to check if a string is a part from many strings in a list

Time:12-07

Say I have a list of file names with different extensions:

ArrayList<String> list = Arrays.asList("filename1.txt", "filename2.txt", "filename2.xml", "filename2.csv", "filename3");

and I would like to check (ideally also count occurrences) if a certain filename exists regardless of the extension.

So I would like to check if filename2 exists in the list. If I use Collections.frequency or contains() it only works with the full name.

Any ideas?

CodePudding user response:

One idea is to use a HashMap<String, List>.

The keys would be the filenames, and the values would be the various extensions.

So you'd check map.containsKey("filename2"). If you want the full file names, you'd concat the key with the all possible extensions in the value list (i.e. .txt,.xml, etc)

CodePudding user response:

You can do this by iterating the list and calling contains() on each String.
In each iteration, if the contains() returns true, you can increment a counter.

Or your can also use regex to match a pattern instead of contains() method and perform even more fine grained matching.

For eg: for filename abc.txt, if you search for filename tx using contains, you would get true return value.
You can handle these scenarios using regex patter match.

CodePudding user response:

public static void main(String[] args) {

        List<String> list = Arrays.asList("filename1.txt", "filename2.txt", "filename2.xml", "filename2.csv", "filename3.txt");

        System.out.println(mapToExtension(list));


    }

    public static Map<String,List<String>> mapToExtension(List<String> list){
        Map<String,List<String>> extensionMap = new HashMap<>();
        for (String filename: list){
            String[] dotSeparator = filename.split("\\.");
            // Assuming last dot separator is the extension
            String ext = dotSeparator[dotSeparator.length-1];
            if (!extensionMap.containsKey(ext)){
                extensionMap.put(ext,new ArrayList<>());
            }
            List<String> sameExtensionList = extensionMap.get(ext);
            // Add it to the list
            sameExtensionList.add(filename);
        }
        return extensionMap;
    }

Once you get a map , you can always check the existing extensions using the map.

CodePudding user response:

You can achieve that in many ways! I will give 2 ways now:

  1. One Using For loop if you are not using Java 8
  2. if you use java 8 you can use lambda expression and get result in 1 single line of code

NOTE: Code has been tested successfully per requirments, (see comments for more info)

    import java.util.Arrays;
    import java.util.List;


     public class Program{

        public static void main(String[] args) {
            
            String fileName="filename2";
            
            List<String> myList = Arrays.asList("filename1.txt", "filename2.txt", "filename2.xml", "filename2.csv", "filename3", "");
            
            long countWithoutLambda = getCountWithoutLambdaExpression(myList, fileName);

            long countWithLambda = getCountWitLambdaExpression(myList, fileName);
            
        }
        
        
        // Method to get filename Without Extension
        public static String getBaseName(String fileName) {
            int index = fileName.lastIndexOf('.');
            if (index == -1) {
                return fileName;
            } else {
                return fileName.substring(0, index);
            }   
        }
        
        // if you don't use java 8 and want a simple loop
        public static long getCountWithoutLambdaExpression(List<String> myList, String fileName){
            long filesCount = 0;
            for(String str : myList){
                if(getBaseName(str).contains(fileName))
                    filesCount  ;
            }
            return filesCount;
        }
        
        
        // if you use Java 8 you can achieve it by using lamda expression
        public static long getCountWitLambdaExpression(List<String> myList, String fileName){
            return myList.stream().filter(p -> getBaseName(p).contains(fileName)).count();
        }
}

CodePudding user response:

If you are using Java 8 or later then you can use Stream API:

List<String> list = Arrays.asList("filename1.txt", "filename2.txt", "filename2.xml", "filename2.csv", "filename3.txt");
List<String> list2 = list.stream()
            .filter(x -> x.indexOf("filename2") >= 0)
            .collect(Collectors.toList());
list2.forEach(str -> System.out.println(str   "  "));
System.out.println("\nfound "   list2.size()   " occurrences");

This code will work for any string you want to search in the List elements, just replace the string "filename2" with the string you wish to find.

Hope it helps.

  •  Tags:  
  • java
  • Related