給定一個字串:
a - 11 h - 19 l - 18 d - 19
我需要先按數字(按降序)然后按字母對其子字串進行排序,以便排序結果具有以下形式:
d - 19 h - 19 l - 18 a - 11
uj5u.com熱心網友回復:
要解決,必須將問題分解為子問題:
- 將輸入字串分解為子字串
- 將每個子字串收集到一個串列中
- 創建一個比較器,比較(子)字串的最后(數字)部分并按降序對它們進行排序,然后按升序對開始部分進行排序
- 將子字串串列轉換回字串
將輸入字串分解為子字串
String regex = "\\w\\s-\\s\\d ";
String input = "a - 11 h - 19 l - 18 d - 19";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);
matcher.toMatchResult().groupCount(); // this should return 4 (won't be used in final code)
將每個子字串收集到一個串列中
List<String> strings = new ArrayList<>();
while (matcher.find()) {
strings.add(matcher.group());
}
上面的代碼將遍歷與正則運算式模式匹配的所有組并將它們添加到串列中。
創建比較器
Comparator<String> compareBySubstring = Comparator.comparing((String s) -> s.substring(s.indexOf(" -")))
.reversed().thenComparing((String s) -> s.substring(0, s.indexOf("-")));
List<String> newList = strings.stream().sorted(compareBySubstring).collect(Collectors.toList());
我創建的比較器比較子字串的最后一部分(破折號之后)并按降序(reversed())對它們進行排序。然后,中間結果從子字串的開頭到破折號按升序排序。基本上它按字母順序對中間結果進行排序,因為子字串以字母開頭。
將子字串串列轉換回字串
StringBuilder buffer = new StringBuilder();
newList.forEach(item -> {
buffer.append(item " "); // done to reinsert the space that separated each substring.
});
我創建了一個測驗程式來運行它:
public class SortBySubstringDemo {
public static void main(String[] args) {
String regex = "\\w\\s-\\s\\d ";
String input = "a - 11 h - 19 l - 18 d - 19";
System.out.println("Input:\n" input);
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);
List<String> strings = new ArrayList<>();
while (matcher.find()) {
strings.add(matcher.group());
}
Comparator<String> compareBySubstring = Comparator.comparing((String s) -> s.substring(s.indexOf(" -")))
.reversed().thenComparing((String s) -> s.substring(0, s.indexOf("-")));
List<String> newList = strings.stream().sorted(compareBySubstring).collect(Collectors.toList());
StringBuilder buffer = new StringBuilder();
newList.forEach(item -> {
buffer.append(item " ");
});
String output = buffer.toString().trim();
System.out.println("Output:\n" output);
}
}
結果如下:
Input:
a - 11 h - 19 l - 18 d - 19
Output:
d - 19 h - 19 l - 18 a - 11
uj5u.com熱心網友回復:
您的具體示例的一種替代方法是使用stream:
- 替換
" - "為" "以獲得由空格分隔的字母和數字的字串。 - 拆分使用
" "以獲得array偶數索引中的字母和奇數索引中的數字。 - 使用偶數索引創建一個
IntStream并將它們映射到一個Map.Entry<String,Integer>使用array[index]作為鍵和array[index 1]作為值。 stream使用先比較值然后比較鍵的比較器對 進行排序。- 將條目映射
stream到帶有key " - " value. - 最后,收集
stream到一個字串,用空格Collectors.joining(" ")分隔每個字串。"letter - number"
總結一個方法:
public static String sort(String str) {
String[] arr = str.replaceAll(" - ", " ").split(" ");
Comparator<Map.Entry<String, Integer>> comparator = Comparator
.comparingInt(Map.Entry<String, Integer>::getValue).reversed()
.thenComparing(Map.Entry::getKey);
return IntStream.range(0, arr.length).filter(i -> i % 2 == 0)
.mapToObj(i -> Map.entry(arr[i], Integer.parseInt(arr[i 1])))
.sorted(comparator).map(entry -> entry.getKey() " - " entry.getValue())
.collect(Collectors.joining(" "));
}
測驗:
String str = "a - 11 h - 19 l - 18 d - 19";
String strSorted = sort(str);
System.out.println(strSorted);
輸出:
d - 19 h - 19 l - 18 a - 11
uj5u.com熱心網友回復:
String s = "a - 11 h - 19 l - 18 d - 19";
record Pair(String string, int number) { }
System.out.println( new Scanner( s ).findAll( "(\\w)\\s-\\s(\\d )" )
.map( matchResult -> new Pair( matchResult.group( 1 ), Integer.parseInt( matchResult.group( 2 ) ) ) )
.sorted( Comparator.<Pair>comparingInt( Pair::number ).reversed().thenComparing( Pair::string ) )
.map( pair -> pair.string() " - " pair.number() )
.collect( Collectors.joining( " " ) ) );
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/439281.html
上一篇:如何在Python中遍歷具有不同開始和停止索引的串列?
下一篇:迭代地將新串列作為值添加到字典中
