猿问

如何使用数组中 png 的名称以两种不同的方式对数组进行排序

我制作了一个包含 8 个 PNG 文件的数组,例如命名为27.png. 我试图将它们显示在 a 中j.label并在它们之间交换,但它们需要按两个不同的事物进行排序。PNG 名称中的“2”表示它是第二便宜的商品,7 表示它是评分第七高的商品。所以34.png将是第三便宜的,评级为 4/8。

我尝试过研究使用index.of,但我找不到在我的情况下使用它的方法。

任何帮助将不胜感激,谢谢大家。


神不在的星期二
浏览 92回答 2
2回答

暮色呼如

public class Main {&nbsp; &nbsp; public static void main(String[] args) {&nbsp; &nbsp; &nbsp; &nbsp; String [] pngs = {"18.png","43.png", "27.png", "62.png", "71.png","34.png", "55.png", "86.png"};&nbsp; &nbsp; &nbsp; &nbsp; //this will sort by cheapest first&nbsp; &nbsp; &nbsp; &nbsp; java.util.Arrays.sort(pngs);&nbsp; &nbsp; &nbsp; &nbsp; printArray(pngs);&nbsp; &nbsp; &nbsp; &nbsp; //to sort by lowest rank first, swap digits, sort, re-swap digits&nbsp; &nbsp; &nbsp; &nbsp; swapFirstTwoDigits(pngs);&nbsp; &nbsp; &nbsp; &nbsp; java.util.Arrays.sort(pngs);&nbsp; &nbsp; &nbsp; &nbsp; swapFirstTwoDigits(pngs);&nbsp; &nbsp; &nbsp; &nbsp; printArray(pngs);&nbsp; &nbsp; &nbsp; &nbsp; //to sort by highest rank first, swap digits, sort, re-swap digits&nbsp; &nbsp; &nbsp; &nbsp; swapFirstTwoDigits(pngs);&nbsp; &nbsp; &nbsp; &nbsp; java.util.Arrays.sort(pngs,java.util.Collections.reverseOrder());&nbsp; &nbsp; &nbsp; &nbsp; swapFirstTwoDigits(pngs);&nbsp; &nbsp; &nbsp; &nbsp; printArray(pngs);&nbsp; &nbsp; }&nbsp; &nbsp; static void swapFirstTwoDigits(String[] array){&nbsp; &nbsp; &nbsp; &nbsp; for (int i = 0; i < array.length; i++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; String s = array[i];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; array[i] = ""+s.charAt(1)+s.charAt(0)+s.substring(2);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; static void printArray(String [] array){&nbsp; &nbsp; &nbsp; &nbsp; for (int i = 0; i < array.length; i++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println(array[i]);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; System.out.println("-------------------");&nbsp; &nbsp; }}

浮云间

如果将这些名称存储在列表中,则可以利用使用比较器的 List#sort 方法。&nbsp;&nbsp;&nbsp;&nbsp;List<String>&nbsp;names&nbsp;=&nbsp;Lists.newArrayList(&nbsp;"35.png",&nbsp;"27.png"&nbsp;); &nbsp;&nbsp;&nbsp;&nbsp;names.sort(&nbsp;Comparator.comparing(&nbsp;(&nbsp;String&nbsp;o&nbsp;)&nbsp;->&nbsp;Integer.parseInt(&nbsp;o.substring(&nbsp;0,&nbsp;1&nbsp;)&nbsp;)&nbsp;) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.thenComparing(&nbsp;o&nbsp;->&nbsp;Integer.parseInt(&nbsp;o.substring(&nbsp;1,&nbsp;2&nbsp;)&nbsp;)&nbsp;)&nbsp;);如果将它们存储在其他集合中,则可以利用 Stream API 从集合中获取流,并使用相同的比较器对流进行排序
随时随地看视频慕课网APP

相关分类

Java
我要回答