1

I am trying to filter strings from an array. For example I have five strings

  1. adcfd
  2. adjnrj
  3. amlkc
  4. nfldkm
  5. cslkls

If I want to create a new array that contains the filtered array, e.g. it starts with 'ad' it will create an array with two elements [adcfd, adjnrj]

or if it starts with 'a' we will get an array with three elements [adcfd, adjnrj, amlkc]

The only thing in my mind is to compare each character from all the strings until we get two 'trues' then we can end the loop.

If there is any function that I don't know, can I give any suggestions?

3
  • Might want to look into regular expressions (regex) if you plan on creating a filter system. Commented Dec 14, 2016 at 3:09
  • 1
    Take a look at docs.oracle.com/javase/8/docs/api/java/lang/String.html and see if you find some way to determine if a string starts with another string. Commented Dec 14, 2016 at 3:10
  • @user306856 Do you know you can accept solution which you think it helps you by checking the tick beside it?? Commented Dec 14, 2016 at 3:23

4 Answers 4

2

There is an easier way in Java 8.

Since Stream API is now available to Java.

public static void main(String[] args)
{
   String[] stringArray = {"adcfd", "adjnrj", "amlkc", "nfldkm", "cslkls"};
   List<String> myList = Arrays.asList(stringArray);
   Object[] result = myList.stream().filter(s -> s.startsWith("ad")).toArray();
   for(Object obj : result){
      System.out.println(obj);
   }
 }

Note this will work only in Java 8.

Sign up to request clarification or add additional context in comments.

Comments

1
    String[] strings = {"adcfd", "adjnrj", "amlkc", "nfldkm", "cslkls"};
    String prefix = "ad";
    String[] result = null;

    // Use String#startsWith
    result = Stream.of(strings).filter(str -> str.startsWith(prefix))
            .collect(Collectors.toSet()).toArray(new String[0]);
    Stream.of(result).forEach(System.out::println); //-> adjnrj adcfd

    // Use String#matches (with regexp)
    result = Stream.of(strings).filter(str -> str.matches("^" + prefix + ".*$"))
            .collect(Collectors.toSet()).toArray(new String[0]);
    Stream.of(result).forEach(System.out::println);  //-> adjnrj adcfd

2 Comments

Why do you use toSet() instead of toList()?
@LukeLee I didn't consider much, just tried to remove duplicated items. toList is also fine if no need to do so.
1

You need to use the startsWith method of String class in java. For example,

public static void main(String args[]) {
    String Str = new String("Welcome to StackOverflow");

    System.out.print("Return Value :" );
    System.out.println(Str.startsWith("Welcome") );

    System.out.print("Return Value :" );
    System.out.println(Str.startsWith("StackOverflow") );
}

It prints:

Return Value :true
Return Value :false

Edit: Previously i didn't give straightforward answer to OP's question as i thought OP will try from my given example. Since others have already shared their answer, i am sharing a simple code snippet that will provide OP the desired output.

String[] strings = {"adcfd", "adjnrj", "amlkc", "nfldkm", "cslkls"};
String prefix = "ad";
ArrayList<String> result = new ArrayList<>();
for (String str : strings) {
    if (str.startsWith(prefix)) {
        result.add(str);
    }
}
System.out.println(result.toString());

It prints:

[adcfd, adjnrj]

Comments

0

I think you can sort String first then you can get all matched String without compare all string element.

an alternative code segment:

public class Demo {
public List<String> test(String[] strs,String filter){
    List<String> res = new LinkedList<>();
    Arrays.sort(strs);
    for(String str:strs){
        if(str.startsWith(filter)){
            res.add(str);
            continue;
        }
        if(str.compareTo(filter)>0){
            return res;
        }
    }
    return res;
}

 public static void main(String[] args){
    String[] strs = {"adcfd","adjnrj","amlkc","nfldkm","cslkls"};
    Demo demo = new Demo();
    String filter = "a";
    System.out.println(demo.test(strs, filter));
 }
}

output:

[adcfd, adjnrj, amlkc]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.