大家好,我是三叔,很高兴这期又和大家见面了,一个奋斗在互联网的打工人。
当我们需要对字符串进行排序时,通常的方法是将字符串转换为字符数组,并对字符数组进行排序。但是,如果我们只需要对单个字符串进行排序,也可以使用一些更简洁的方法。本文笔者将介绍如何使用Java8对字符串进行排序。
使用数组进行排序:Arrays.sort()
直接上代码:
public static void main(String[] args) {
String str = "hello";
char[] charArray = str.toCharArray();
Arrays.sort(charArray);
String newStr = new String(charArray);
System.out.println(newStr);
}
打印看看:
上面这个例子将字符串"hello"转换为字符数组,然后使用Arrays.sort()方法对字符数组进行排序。最后使用String类的构造函数将排序后的字符数组合并为一个新的字符串。
Java8流式处理 chars() 适用于单个字符串!!!
String.chars()方法将字符串转换为整数流,并对其进行排序。
public static void main(String[] args) {
String str = "hello";
String newStr = str.chars()
.sorted()
.collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
.toString();
System.out.println(newStr);
}
打印如下:
将字符串"hello"转换为整数流,然后使用sorted()方法对其进行排序。最后,我们将排序后的整数流转换回字符串,并将其打印输出。
请注意,这种方法只适用于对单个字符串进行排序!!!