我正在嘗試了解 Collections 和 Stream。
我已經拆分了下面的句子并保留了每個字母的位置(我忽略了空格/空白):“Hello Word!”
private static final String text = "Hello Word!";
static Map<String, List<Integer>> charsIndex = new HashMap<>();
static void charsIndex() {
List<Character> charsList = text
.chars()
.mapToObj(e -> (char) e)
.toList();
System.out.println(charsList);
int position = 0;
for (Character c : charsList) {
if(!c.toString().isBlank()){
charsIndex.computeIfAbsent(c.toString(),
addCharPosition -> new ArrayList<>()).add(position);
}
position = 1;
}
System.out.println(charsIndex);
}
結果:
[H, e, l, l, o, , W, o, r, d, !] (charsList)
{!=[10], r=[8], d=[9], e=[1], W=[6], H=[0], l=[2, 3], o=[4, 7]} (字符索引)
我怎樣才能對字符進行排序并與空白一起重建我的單詞?
我嘗試這樣:
static void charsToString(){
charsIndex.forEach((character, l) -> l.forEach(position -> {
}));
}
uj5u.com熱心網友回復:
您可以通過以下步驟根據索引映射恢復原始字串:
根據字符的位置對字符進行排序。因為映射中的每個條目都將一個字符與多個索引相關聯,為此您需要定義一個輔助型別,保存對單字符字串的參考和該字符的不同位置。讓我們稱之為
CharPosition生成一個串列
CharPosition(已排序)。要恢復空白,我們可以定義一個陣列,其長度為最高索引 1。然后用串列的內容填充該陣列
CharPosition。最后,在陣列元素上創建一個流,用空格替換所有空值并
String使用 Collector生成結果joining()。
為了簡潔起見,我將使用Java 16 記錄來實作CharPosition:
public record CharPosition(String ch, int pos) {}
這就是上述邏輯的實作方式:
static void charsToString() {
List<CharPosition> charPositions = charsIndex.entrySet().stream()
.flatMap(entry -> entry.getValue().stream()
.map(pos -> new CharPosition(entry.getKey(), pos))
)
.sorted(Comparator.comparingInt(CharPosition::pos))
.toList();
int wordLen = charPositions.get(charPositions.size() - 1).pos() 1;
String[] word = new String[wordLen];
charPositions.forEach(c -> word[c.pos()] = c.ch());
String result = Arrays.stream(word)
.map(str -> Objects.requireNonNullElse(str, " "))
.collect(Collectors.joining());
System.out.println(result);
}
輸出:
Hello Word!
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/533935.html
