Java 如何根据字符串的长度对其进行分组? 公共类排序文本{ 公共静态void main(字符串[]args)引发IOException{ String readline=“我有一个带单词的句子”; String[]words=readline.split(“”); sort(单词,(a,b)->Integer.compare(b.length(),a.length()); 对于(inti=0;i
使用流API很容易:Java 如何根据字符串的长度对其进行分组? 公共类排序文本{ 公共静态void main(字符串[]args)引发IOException{ String readline=“我有一个带单词的句子”; String[]words=readline.split(“”); sort(单词,(a,b)->Integer.compare(b.length(),a.length()); 对于(inti=0;i,java,Java,使用流API很容易: 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)
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]);
}
}
final Map<Integer, List<String>> lengthToWords = Arrays.stream(words)
.collect(Collectors.groupingBy(String::length, TreeMap::new, Collectors.toList()));
如果您是初学者或不熟悉stream API:
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]);
}
}
final Map<Integer, List<String>> lengthToWords = Arrays.stream(words)
.collect(Collectors.groupingBy(String::length, TreeMap::new, Collectors.toList()));
publicstaticvoidmain(字符串[]args){
String readline=“我有一个带单词的句子”;
String[]words=readline.split(“”);
sort(单词,(a,b)->Integer.compare(b.length(),a.length());
//声明一个变量以保存当前字符串长度
int currength=-1;
对于(int i=0;我能再解释一下你的问题吗?我有一个句子。我必须把句子拆分,并按字符长度对单词进行分组。输入:我有一个包含单词的句子预期输出:8-句子5-单词4-包含1-i“字符长度”?你的意思是字长吗?到目前为止,你只根据字长对单词进行排序,但没有努力对它们进行“分组”。为什么?你的尝试在哪里?在分割输入后,你可以使用映射按其长度对子字符串进行分组。(a,b)->整数。比较(b.length(),a.length())
也可以写成比较器。comparingInt(字符串::长度)