Java单词频率按长度排序,然后按字母顺序排序 导入java.lang.Character; 导入java.io.EOFException; 导入java.util.ArrayList; 导入java.util.Collections; 导入java.util.Comparator; 导入java.util.List; 公共类分析{ 静态字符串arr[];/**在数组中存储未排序的单词**/ 公共静态整数计数=0; 静态字符a,s; 静态字符串单词=”; 公共静态void main(字符串[]args)引发EOFEException{ SimpleCharacterReader流=新的SimpleCharacterReader(); 列表=新的ArrayList(); 字符串str=“”; /**需要知道我们有多少词**/ 计数(流); SimpleCharacterReader st=新的SimpleCharacterReader(); 商店(街);; /**在列表中存储有效单词,以便以后排序**/ 对于(int i=0;iSystem.out.printf(“%d-%w:%d%n”,word.length(),word,freq)); }

Java单词频率按长度排序,然后按字母顺序排序 导入java.lang.Character; 导入java.io.EOFException; 导入java.util.ArrayList; 导入java.util.Collections; 导入java.util.Comparator; 导入java.util.List; 公共类分析{ 静态字符串arr[];/**在数组中存储未排序的单词**/ 公共静态整数计数=0; 静态字符a,s; 静态字符串单词=”; 公共静态void main(字符串[]args)引发EOFEException{ SimpleCharacterReader流=新的SimpleCharacterReader(); 列表=新的ArrayList(); 字符串str=“”; /**需要知道我们有多少词**/ 计数(流); SimpleCharacterReader st=新的SimpleCharacterReader(); 商店(街);; /**在列表中存储有效单词,以便以后排序**/ 对于(int i=0;iSystem.out.printf(“%d-%w:%d%n”,word.length(),word,freq)); },java,Java,您需要将单词收集到一个树状图中,该树状图支持有序键,并可能提供一个 每个单词的频率将存储为一个值。它可以使用函数进行累积 假设所有单词都通过方法store读入数组arr,则代码可按如下方式更新: //类分析,主方法 商店(街);; /**在已排序的映射中存储有效单词并计算单词频率**/ //使用自定义比较器作为lambda创建树映射 映射频率=新树映射((s1,s2)->Integer.compare(s1.length(),s2.length())==0?s1.compareTo(s2):In

您需要将单词收集到一个
树状图中,该树状图支持有序键,并可能提供一个

每个单词的频率将存储为一个值。它可以使用函数进行累积

假设所有单词都通过方法
store
读入数组
arr
,则代码可按如下方式更新:

//类分析,主方法
商店(街);;
/**在已排序的映射中存储有效单词并计算单词频率**/
//使用自定义比较器作为lambda创建树映射
映射频率=新树映射((s1,s2)->Integer.compare(s1.length(),s2.length())==0?s1.compareTo(s2):Integer.compare(s1.length(),s2.length());
for(字符串字:arr){
if(null!=单词&!“.equals(单词)){
合并频率(单词,1,(acc,1)->acc+1);
}
}
打印(频率);//代替打印(列表);
接下来,需要更新方法
print
,以处理地图而不是列表:

公共静态无效打印(地图频率){
frequency.forEach((word,freq)->System.out.printf(“%d-%w:%d%n”,word.length(),word,freq));
}

此外,还可以使用流API使用定制的比较器对单词进行排序,该比较器由
比较器链组成。比较(字符串::长度)。然后比较(字符串::比较器)
,然后使用
收集器收集频率。toMap
到维护插入顺序的
LinkedHashMap

//类分析,主方法
商店(街);;
映射频率=阵列
.stream(arr)//流
.filter(word->null!=word&&!“.equals(word))
.sorted(//sort
Comparator.comparingInt(字符串::长度)
.thenComparing(String::compareTo)//或compareToIgnoreCase(如果需要)
)
.collect(collector.toMap)(
word->word,//使用word作为键
word->1,//1作为初始值
整数::求和,//合并函数以计数频率
LinkedHashMap::新建//保持插入顺序(按排序键)
));
打印(频率);//代替打印(列表);

您应该使用字符串#equals()来检查字符串的相等性,而不是==或!=。吹毛求疵:既然字符是Java中的一种类型,我就不给它取名为SimpleCharacterReader,而是取名为SimpleFrequencyReader要获得你的角色而不是静态方法?我指的是我得到的simplecharacterreader和我也得到的Icharacterreader我是Java新手,所以任何人的建议我都会非常感谢Anks Alex!我将在何处插入创建比较器作为lambda?对不起,我是java新手。非常感谢!在
TreeMap
的构造函数中,我不完全确定在我自己的代码中实现这一点的位置。有什么建议吗?比
    print(frequency); // instead of print(list);
    }
    public static List<String> sort(List<String> list){
        /** We use string compare to sort the list by length first then Collections.sort will sort it alphabetically  **/
        Collections.sort(list, new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                if (o1.length() < o2.length()) { /**Second string length is greater than first string length**/
                    return -1;
                } else if (o1.length() > o2.length()) {/**Second string length is less than first string length**/
                    return 1;
                } else {        /** Equal **/
                    return o1.compareTo(o2);
                }
            }
        });
        return list;
    }
    /** Simply prints the length and sorted words. Sorted by their length first then alphapetically. **/
    public static void print(Map<String, Integer> frequency) {
        frequency.forEach((word, freq) -> System.out.printf("%d - %w: %d%n", word.length(), word, freq));
    }
        }
    }
    /** Counts how many words **/
    public static void count(SimpleCharacterReader stream) {
        try {
            while (true) {
                a = getReader(stream);
                /** When a space, next line or tab is met, we assume a word was met. **/
                if ((a == ' ') || (a == '\n') || (a == '\t')) {
                    count++;
                }
            }
        } catch (EOFException eof) {
            stream.Dispose();
        }
        arr = new String[count];
    }
    /** Gets the characters **/
    public static char getReader(ICharacterReader reader) throws EOFException {
        return reader.GetNextChar();
    }
    /** Store unsorted words in array **/
    public static void store(ICharacterReader info) throws EOFException {
        int i = 0;
        while (i < count) {
            s = info.GetNextChar();
            if (Character.isLetterOrDigit(s)) {
                word += Character.toString(s);
            } else if (s == ' ' || s == '\n' || s == '\t') {
                arr[i++] = word;
                word = "";
            }
        }
    }
}
import java.io.EOFException;
import java.util.Random;

public class SimpleCharacterReader implements ICharacterReader {
    private int m_Pos = 0;

    public static final char lf = '\n';

    private String m_Content = "It was the best of times, it was the worst of times," + 
    lf +
    "it was the age of wisdom, it was the age of foolishness," + 
    lf +
    "it was the epoch of belief, it was the epoch of incredulity," + 
    lf +
    "it was the season of Light, it was the season of Darkness," + 
    lf +
    "it was the spring of hope, it was the winter of despair," + 
    lf +
    "we had everything before us, we had nothing before us," + 
    lf +
    "we were all going direct to Heaven, we were all going direct" + 
    lf +
    "the other way--in short, the period was so far like the present" + 
    lf +
    "period, that some of its noisiest authorities insisted on its" + 
    lf +
    "being received, for good or for evil, in the superlative degree" + 
    lf +
    "of comparison only." + 
    lf +
    "There were a king with a large jaw and a queen with a plain face," + 
    lf +
    "on the throne of England; there were a king with a large jaw and" + 
    lf +
    "a queen with a fair face, on the throne of France.  In both" + 
    lf +
    "countries it was clearer than crystal to the lords of the State" + 
    lf +
    "preserves of loaves and fishes, that things in general were" + 
    lf +
    "settled for ever";

    Random m_Rnd = new Random();

    public char GetNextChar() throws EOFException {

        if (m_Pos >= m_Content.length()) {
            throw new EOFException();
        }

        return m_Content.charAt(m_Pos++);

    }

    public void Dispose() {
        // Do nothing
    }
}
import java.io.EOFException;

public interface ICharacterReader {

    char GetNextChar() throws EOFException;

    void Dispose();
}
import java.lang.Character;
import java.io.EOFException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class Analyse {
    static String arr[];        /** Store unsorted words in array**/
    public static int count = 0;
    static char a, s;
    static String word = "";

    public static void main(String[] args) throws EOFException {

        SimpleCharacterReader stream = new SimpleCharacterReader();
        List<String> list = new ArrayList<>();
        String str = "";
        /** Need to know how may words we have**/
        count(stream);
        SimpleCharacterReader st = new SimpleCharacterReader();
        store(st);
        /**Store valid words in list to sort later**/
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] != " " && arr[i] != null) {
                str = arr[i];
            }
            list.add(str);
        }
        sort(list); /**Sort list**/
        print(list);/**Print list**/
    }
    public static List<String> sort(List<String> list){
        /** We use string compare to sort the list by length first then Collections.sort will sort it alphabetically  **/
        Collections.sort(list, new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                if (o1.length() < o2.length()) { /**Second string length is greater than first string length**/
                    return -1;
                } else if (o1.length() > o2.length()) {/**Second string length is less than first string length**/
                    return 1;
                } else {        /** Equal **/
                    return o1.compareTo(o2);
                }
            }
        });
        return list;
    }
    /** Simply prints the length and sorted words. Sorted by their length first then alphapetically. **/
    public static void print(List<String> list) {
        for (int i = 0; i < arr.length; i++) {
            System.out.println(list.get(i).length() + " - " + list.get(i));
        }
    }
    /** Counts how many words **/
    public static void count(SimpleCharacterReader stream) {
        try {
            while (true) {
                a = getReader(stream);
                /** When a space, next line or tab is met, we assume a word was met. **/
                if ((a == ' ') || (a == '\n') || (a == '\t')) {
                    count++;
                }
            }
        } catch (EOFException eof) {
            stream.Dispose();
        }
        arr = new String[count];
    }
    /** Gets the characters **/
    public static char getReader(ICharacterReader reader) throws EOFException {
        return reader.GetNextChar();
    }
    /** Store unsorted words in array **/
    public static void store(ICharacterReader info) throws EOFException {
        int i = 0;
        while (i < count) {
            s = info.GetNextChar();
            if (Character.isLetterOrDigit(s)) {
                word += Character.toString(s);
            } else if (s == ' ' || s == '\n' || s == '\t') {
                arr[i++] = word;
                word = "";
            }
        }
    }
}