简体   繁体   中英

How to remove String from an array by checking length and comparing text in Java?

How to remove String from an array by checking length and comparing text in Java?

Suppose user search for "Hi Tonki with Monkey"

String[] pattern = userSearchString.toLowerCase().split("\\s");

1) We want to remove "With" from pattern and

2) also want to remove pattern with less then 3 size like "Hi".

So pattern should contain Tonki and Monkey only.

It will be fuitful if anyone can suggest method from Apache Commons or Guava.

Using Java 1.6

A Java 8 solution would be to Stream the array and filter only the elements that you want, and collect it back into an array:

Arrays.stream(pattern)
      .filter(word -> !word.equals("with"))
      .filter(word -> word.length() >= 3)
      .toArray(String[]::new);

A pre-Java 8 solution would be to filter the array manually. However, we'll have to create a new array; but because we do not know the size of the new array in advance, we can use a List<String> and collect it to an array after adding its respective elements:

List<String> list = new ArrayList<>();

for (String word : pattern) {
    if (word.length() < 3 || word.equals("with")) {
        continue;
    }

    list.add(word);
}

list.toArray(new String[list.size()]);

There's no need to use external libraries if they aren't required!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM