【问题标题】:Printing from a dictionary Java从字典 Java 打印
【发布时间】:2019-01-23 22:53:36
【问题描述】:

我想使用字典系统打印文本中每个字符的出现:

例如:文本是“我喜欢苹果”

控制台输出如下:

'i' 在以下位置出现 2 次:1, 4

'l' 在位置上出现了 2 次:3, 11

..

到目前为止,我已经得到了这个

String text = "text";
HashMap<Integer, String> dictionary = new HashMap<Integer, String>();

for (int i = 0; i < text.length(); i++) {
    dictionary.put(i, String.valueOf(text.charAt(i)));
}

基本上只是将每个字母添加到字典中的键值中,但我不知道如何进行打印...

【问题讨论】:

  • @Aomine 我相信这并不是真正的重复:另一个问题想要使用正则表达式的解决方案 - 这个问题想要使用字典并且也想要职位。不同的问题。
  • @CPerkins 确定,重新打开。

标签: java dictionary printing


【解决方案1】:

此代码使用字典并以请求的确切格式打印正确答案:

import java.util.ArrayList;
import java.util.HashMap;

public class TestDriver {

public static void main(String[] args) {    

    String text = "i like apples";  
    char[] textArray = text.toCharArray();

    //a dictionary that will hold the letter as the key and a list of it's positions as the value.
    HashMap<Character, ArrayList<Integer>> dictionary = new HashMap<Character, ArrayList<Integer>>();

    //loop through the text to check each letter
    for (int i = 0; i < textArray.length; i++) {            

        //if you've already checked this letter, skip to the next one
        if(dictionary.containsKey(textArray[i])) {
            continue;
        }       

        //add the letter's position to its position list
        ArrayList<Integer> positionList = new ArrayList<>();
        positionList.add(i);

        //compare the remaining letters in the text to the current letter
        for (int j = i+1; j < textArray.length; j++) {

                //if a letter matches, add it's position to the list
                if(textArray[i] == textArray[j]) {
                positionList.add(j);
            }   
        }               

        //add the letter and its list of positions to the dictionary
        dictionary.put(textArray[i], positionList);
    }

    //format the response
    for(char key : dictionary.keySet()) {
        ArrayList<Integer> positions = new ArrayList<>();
        positions = dictionary.get(key);
        System.out.println(key + " has an occurance of " + positions.size() + " on positions: " + positions);           
        }
    }
}

打印到控制台:

  has an occurance of 2 on positions: [1, 6]
p has an occurance of 2 on positions: [8, 9]
a has an occurance of 1 on positions: [7]
s has an occurance of 1 on positions: [12]
e has an occurance of 2 on positions: [5, 11]
i has an occurance of 2 on positions: [0, 3]
k has an occurance of 1 on positions: [4]
l has an occurance of 2 on positions: [2, 10]

【讨论】:

  • 你需要使用字典吗?
  • 是的,我知道如何在不使用字典的情况下编写解决方案,无论如何这个解决方案更适合我,我实际上可以比最初的解决方案更好地理解它。感谢您的精彩回答!
  • 欢迎您,如果您想对其中任何一个进行解释,我可以在代码中添加 cmets lmk
  • 这也很有帮助!虽然我有点理解这是如何工作的,主要是...... XD
【解决方案2】:

这就是我的做法:

String[] tempArray = data.split("");
IntStream.rangeClosed(1, tempArray.length)            
         .boxed()
         .collect(groupingBy(index -> tempArray[index-1].toUpperCase()))
         .forEach((k, v) -> System.out.println(k + " has an occurrence of " +
                     v.size() + " times on positions " + v.stream()
                    .map(Object::toString).collect(joining(","))));
  • 首先将字符串拆分为表示为字符串的各个字符
  • 使用IntStream.range 生成索引
  • 利用groupingBy 按单个字符分组,并将值作为List&lt;Integer&gt; 表示字符出现的索引
  • 最后,使用forEach 格式化数据并打印到控制台。

给定数据设置如下:

String data = "I like apples";

这会产生输出:

P has an occurrence of 2 times on positions 9,10
  has an occurrence of 2 times on positions 2,7
A has an occurrence of 1 times on positions 8
S has an occurrence of 1 times on positions 13
E has an occurrence of 2 times on positions 6,12
I has an occurrence of 2 times on positions 1,4
K has an occurrence of 1 times on positions 5
L has an occurrence of 2 times on positions 3,11

请注意,上述解决方案也将空格视为字符,如果您不希望在输出中出现此内容,请使用filter 操作将其排除:

IntStream.rangeClosed(1, tempArray.length)
         .filter(index -> !tempArray[index-1].trim().isEmpty())
         .boxed()
         .collect(groupingBy(index -> tempArray[index-1].toUpperCase()))
         .forEach((k, v) -> System.out.println(k + " has an occurrence of " +
                     v.size() + " times on positions " + v.stream()
                    .map(Object::toString).collect(joining(","))));

【讨论】:

  • IntStream 也像字典一样工作吗?我不明白在这种情况下如何创建字典,从我一直在学习的课程中我读到您可以使用 HashMap 创建字典,所以我继续使用它,并且有一个练习要求执行上述操作,但我无法弄清楚如何为练习打印。
  • @David groupingBy 创建字典(在 java 中称为 Map)。例如,如果你做了Map&lt;String, List&lt;Integer&gt;&gt; result = IntStream.rangeClosed(1, tempArray.length) .filter(index -&gt; !tempArray[index-1].trim().isEmpty()) .boxed() .collect(groupingBy(index -&gt; tempArray[index - 1].toUpperCase()));,你就会有一个元素字典到它们的索引。然后,您可以对其进行迭代以按照您的方式对其进行格式化。
  • 哦,好的,很酷,我需要阅读有关 IntStream 提供的功能的更多信息。感谢您的好评!!由于我开始接触复杂的东西,所以我需要去练习更多的基础知识......
【解决方案3】:

你可以尝试如下

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class GenericPlayAround {
    public static void main(String[] args) throws InterruptedException {
        String text = "I like apples";
        Map<Character, List<Integer>> dictionary = new HashMap<Character, List<Integer>>();

        for (int i = 1; i <= text.length(); i++) {
            Character c = text.charAt(i-1);
            List<Integer> list;
            if (dictionary.containsKey(c)) {
                list = dictionary.get(c);
            }
            else {
                list = new ArrayList<Integer>();
                dictionary.put(c, list);

            }
            list.add(i);
        }

        System.out.println(dictionary);
    }
}

输出是

{ =[2, 7], p=[9, 10], a=[8], s=[13], e=[6, 12], I=[1], i=[4], k=[5], l=[3, 11]}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-26
    • 1970-01-01
    相关资源
    最近更新 更多