【发布时间】:2020-02-03 01:41:33
【问题描述】:
我正在尝试将String(存储在ArrayList)递归地拆分为固定数量的单词(不是字符)。
例如,假设我有一个 ArrayList,其中包含以下两个 String 短语:
ArrayList<String> words = new ArrayList<String>();
words.add("key1 key2 key3 key4 key5 key6 key7");
words.add("key11 key12 key13 key14 key15 key16 key17");
我想分成 5 个单词的块 (int desiredListSize = 5;) - 这将产生以下两个列表:
清单 1:
word1 word2 word3 word4 word5
word2 word3 word4 word5 word6
word3 word4 word5 word6 word7
清单 2:
word11 word12 word13 word14 word15
word12 word13 word14 word15 word16
word13 word14 word15 word16 word17
然后将上面的每个列表添加到 List of Lists 数组中,因此输出格式为:ArrayList<ArrayList<String>()
到目前为止,以下代码片段解决了大部分问题:
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
public static void splitListIntoWords()
{
int desiredListSize = 5;
final ArrayList<String> textWords = new ArrayList<String>();
textWords.add("key1 key2 key3 key4 key5 key6 key7");
textWords.add("key11 key12 key13 key14 key15 key16 key17");
final List<List<String>> listOfLists = textWords.stream().flatMap(w -> {
final String[] wordList = StringX.splitStrIntoWordsRtrnArr(w); // w.split(" ");
int calculatedListSize = (wordList.length < desiredListSize) ? wordList.length : desiredListSize;
return IntStream.range(0, Math.min(wordList.length - (calculatedListSize - 1), wordList.length)).mapToObj(i -> i ).flatMap(i -> Stream.of(
IntStream.range(i, Math.min(i+desiredListSize, wordList.length)).mapToObj(j -> wordList[j])
.collect(Collectors.toList())));
}) .collect(Collectors.toList());
for (int counter = 0; counter < listOfLists.size(); counter++) {
System.out.println("LIST: " + counter);
System.out.println(listOfLists.get(counter).toString());
}
}
产生以下输出:
LIST: 0
[key1, key2, key3, key4, key5]
LIST: 1
[key2, key3, key4, key5, key6]
LIST: 2
[key3, key4, key5, key6, key7]
LIST: 3
[key11, key12, key13, key14, key15]
LIST: 4
[key12, key13, key14, key15, key16]
LIST: 5
[key13, key14, key15, key16, key17]
然而理想的输出是:
LIST 0:
key1 key2 key3 key4 key5
key2 key3 key4 key5 key6
key3 key4 key5 key6 key7
LIST 1:
key11 key12 key13 key14 key15
key12 key13 key14 key15 key16
key13 key14 key15 key16 key17
然后应将上述两个列表添加到listOfLists。
注意期望的输出每个列表如何存储对字符串的操作结果:key1 key2 key3 key4 key5 作为单个 String(每个单词之间有一个空格)不是列表。
换句话说,当调用listOfLists.get(0);时,应该得到一个列表,其中包含对words.add("key1 key2 key3 key4 key5 key6 key7");的操作结果,当调用listOfLists.get(1);时,应该得到对words.add("key11 key12 key13 key14 key15 key16 key17");的操作结果当然,如果有原始textWords 列表中的两个以上条目然后listOfLists 将包含相应数量的列表。
谢谢!
【问题讨论】: