【问题标题】:Retrieve word(s) from characters using map使用地图从字符中检索单词
【发布时间】:2022-11-12 11:28:04
【问题描述】:

我正在尝试了解集合和流。

我已经拆分了下面的句子并保留了每个字母的位置(我忽略了空格/空白): “你好字!”

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 -> {

  }));
}

【问题讨论】:

  • 您是否考虑过使用 StringBuilder,您可以在其中将字符设置到正确的位置?
  • 发件人:{!=[10], r=[8], d=[9], e=[1], W=[6], H=[0], l=[2, 3], o=[4, 7]} 收件人:"Hello Word!"@AlexanderIvanchenko

标签: java collections java-stream


【解决方案1】:

您可以通过以下步骤根据索引映射恢复原始字符串:

  • 根据字符的位置对字符进行排序。因为映射中的每个条目都将一个字符与多个索引相关联,因此您需要定义一个辅助类型,保存对单字符字符串的引用和该字符的不同位置。我们就叫它CharPosition

  • 生成CharPosition 的列表(已排序)。

  • 要恢复空白,我们可以定义一个数组,其长度为最高索引 + 1。然后用CharPosition 列表的内容填充这个数组。

  • 最后,在数组元素上创建一个流,用空格替换所有空值并使用收集器joining() 生成结果String

为了简洁起见,我将使用Java 16 record 来实现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!

【讨论】:

    猜你喜欢
    • 2021-07-10
    • 2019-10-09
    • 1970-01-01
    • 1970-01-01
    • 2015-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多