public class sortingtext {
public static void main(String[] args) throws IOException {
String readline="i have a sentence with words";
String[] words=readline.split(" ");
Arrays.sort(words, (a, b)->Integer.compare(b.length(), a.length()));
for (int i=0;i<words.length;i++)
{
int len = words[i].length();
int t=0;
System.out.println(len +"-"+words[i]);
}
}
输入:
我有一个单词的句子
我的代码拆分了一个字符串,然后应该打印每个单词及其长度。
我得到的输出如下:
8个句子
5个字
4-有
4-with
1-I
1-a
我想将长度相同的单词归为一组:
8个句子
5个字
4-具有,带有
1- I,a
但是我不知道如何对它们进行分组。
答案 0 :(得分:2)
易于使用流API:
final Map<Integer, List<String>> lengthToWords = new TreeMap<>(
Arrays.stream(words)
.collect(Collectors.groupingBy(String::length))
);
该流按长度将单词分组到一个映射中(实现细节,但它将是一个HashMap),TreeMap
然后根据键(单词长度)对该映射进行排序。
或者,您可以像这样编写它,效率更高,但我认为可读性较低。
final Map<Integer, List<String>> lengthToWords = Arrays.stream(words)
.collect(Collectors.groupingBy(String::length, TreeMap::new, Collectors.toList()));
答案 1 :(得分:1)
如果您是初学者或不熟悉Stream API:
public static void main(String[] args) {
String readline= "i have a sentence with words";
String[] words = readline.split(" ");
Arrays.sort(words, (a, b)->Integer.compare(b.length(), a.length()));
// declare a variable to hold the current string length
int currLength = -1;
for(int i = 0; i<words.length; i++){
if(currLength == words[i].length()){
// if currLength is equal to current word length just append a comma and this word
System.out.print(", "+words[i]);
}
else{
// if not update currLength, jump to a new line and print new length with the current word
currLength = words[i].length();
System.out.println();
System.out.print(currLength+ " - "+words[i]);
}
}
}
注意:println(“ ...”)方法将打印字符串“ ...”,并将光标移至新行。相反,print(“ ...”)方法仅打印字符串“ ...”,但不会将光标移动到新行。因此,后续的打印指令将在同一行上打印。也可以使用不带参数的println()方法将光标置于下一行。