java中根据字符串排序
时间: 2024-06-10 16:04:10 浏览: 22
在Java中,可以使用Collections.sort()方法对字符串进行排序。但是,默认的字符串比较排序只会考虑字符的顺序,而不会考虑多个数字的情况。例如,在默认排序中,字符串"15"会被认为比"4"小,因为第一个字符"1"比"4"对应的ASCII的顺序要小。如果想要根据数字的大小进行排序,可以使用自定义的比较器。下面是一种实现方式:
List<String> strList = Arrays.asList(new String[]{"5栋", "7栋", "4栋", "15栋", "24栋", "涉外国际7栋", "涉外国际6栋", "B666栋", "B17栋", "B1栋","A45栋","A22栋"});
Collections.sort(strList, (o1, o2) -> {
int num1 = Integer.parseInt(o1.replaceAll("\\D+",""));
int num2 = Integer.parseInt(o2.replaceAll("\\D+",""));
return Integer.compare(num1, num2);
});
这段代码将根据字符串中的数字进行排序,最终输出的结果将按照数字的大小进行排序。比如,"4栋"会排在"5栋"的前面,"15栋"会排在"24栋"的前面。
相关问题
java map根据比较字符串排序
Java中的Map是一种键值对的数据结构,其中键和值都可以是任何类型的对象。Map的类型包括HashMap、ConcurrentHashMap、LinkedHashMap和TreeMap等。其中,HashMap和ConcurrentHashMap是最常用的两种Map类型,它们的区别在于线程安全性和迭代器的一致性。HashMap是非线程安全的,而ConcurrentHashMap是线程安全的。另外,LinkedHashMap
java lambda表达式 字符串排序
Java Lambda表达式是Java 8中引入的一种新特性,它可以使代码更加简洁、易读、易维护。在字符串排序中,我们可以使用Lambda表达式来实现根据字符串长度进行排序。具体实现可以参考以下代码:
```
String[] strings = new String[]{"123","avbs","asdasd","74365222222"};
Arrays.sort(strings, (o1, o2) -> o1.length() - o2.length());
System.out.println(Arrays.toString(strings));
```
上述代码中,我们使用Arrays类的sort方法对字符串数组进行排序,Lambda表达式`(o1, o2) -> o1.length() - o2.length()`表示根据字符串长度进行排序。其中,`o1`和`o2`分别表示要比较的两个字符串,`o1.length() - o2.length()`表示按照字符串长度从小到大排序。
如果要按照字符串长度从大到小排序,只需要将Lambda表达式改为`(o1, o2) -> o2.length() - o1.length()`即可。
在sortByLength方法中,我们可以将上述代码放入其中,将结果进行输出即可。
相关推荐
![text/x-java](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)