[英]Most simple and most efficient ways of filtering a list in Java?
我想從傳入的 stream 推文中的每個短語中過濾不相關的詞。
我可以像這樣使用 ArrayList 這樣做:
import java.util.ArrayList;
// Example Tweet
String tweetText = "Awful glad vaccine is coming at last! #COVID19";
// First convert tweet text to array of words
String text = tweetText
.replaceAll("\\p{Punct}", "")
.replaceAll("\\r|\\n", "")
.toLowerCase();
String[] words = text.split(" ");
// We define an array of irrelevant words to be filtered out
String[] irrelevantWords = {"is", "at", "http", "https", "football"};
// first we create an extensible ArrayList to add filtered words to
ArrayList<String> filteredWords = new ArrayList<String>();
// we assume each word is relevant to begin with...
boolean relevant;
// ... and then we check by iterating over each word...
for (String w : words){
// ... assuming initially that it is relevant ...
relevant = true;
// ... and iterating over each irrelevant word ...
for (String irrelevant : irrelevantWords){
// ... and if a word is the same as an irrelevant word
if (w.equals(irrelevant)){
// ... we know that it is not relevant.
relevant = false;
}
}
// If, having compared the word to all the irrelevant words,
// it is still found to be relevant, we add it to our ArrayList.
if (relevant == true){filteredWords.add(w);}
}
// NB: This is not the most efficient method of filtering words,
// but it is the most simple to understand and implement.
System.out.println(filteredWords);
但是,雖然這對於 Java 的新手來說很容易理解和實現(基本上它只依賴於迭代循環,盡管我們必須導入 ArrayList),但效率很低。
執行此操作的最佳方法(最簡單或更有效)是什么?
從字符串中過濾不相關單詞的預設列表的最簡單方法是使用正則表達式替換。 以下代碼刪除所有出現的單詞bad
和words
,但不包括badass
和nicewords
:
String tweet = ...;
String filteredTweet = tweet.replaceAll("(?<=( |^))(bad|words)(?=( |$))", "");
您可以向此列表添加更多單詞甚至正則表達式,以|
分隔 .
這是一種方法。 我在列表中添加了一個詞
// Example Tweet
String tweetText = "Awful glad vaccine is coming at last! #COVID19";
// We define an array of irrelevant words to be filtered out
String[] irrelevantWords = {"is", "at", "http", "https", "last", "football"};
for (String irr : irrelevantWords) {
tweetText = tweetText.replaceAll("\\s+\\b"+irr+"\\b","");
}
System.out.println(tweetText);
印刷
Awful glad vaccine coming! #COVID19
絕對更簡單,但效率不高。 但是正則表達式也不一定有效。 它們是簡單地執行任務的一般過程。 因此有額外的開銷。 通常編寫自定義解析器效率更高,但肯定不會更簡單。
使用哈希集存儲不相關的詞。
Set<String> irrelevantWords = new HashSet<String>();
將單詞添加到該集合並使用irrelevantWords.contains(word)
檢查單詞是否不相關。
哈希集的查找是 O(1) 對列表/數組的 O(n)。 由於您在循環中使用查找,這將大大提高您的性能。
如果您使用 collections 工作,生活會更輕松:
Set<String> irrelevantWords = Set.of("is", "at", "http", "https", "football"); // Actually a HashSet
List<String> filteredWords = Arrays.stream(text.split(" +"))
.filter(word -> !irrelevantWords.contains(word))
.collect(Collectors.toList());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.