Custom Comparator
You'll have to extract the number part, possibly using some regular expression, and then use that to sort. A custom Comparator
might encapsulate the custom numerical comparison for you.
import java.util.*;
import java.util.regex.*;
// Sort strings by last integer number contained in string.
class CompareByLastNumber implements Comparator<String> {
private static Pattern re = Pattern.compile("[0-9]+");
public boolean equals(Object obj) {
return obj != null && obj.getClass().equals(getClass());
}
private int num(String s) {
int res = -1;
Matcher m = re.matcher(s);
while (m.find())
res = Integer.parseInt(m.group());
return res;
}
public int compare(String a, String b) {
return num(a) - num(b);
}
public static void main(String[] args) {
Arrays.sort(args, new CompareByLastNumber());
for (String s: args)
System.out.println(s);
}
}
Avoiding the IllegalStateException
Referring to your updated question: the exception you encounter is because you attempt to iterate over the DirectoryStream
multiple times. Quoting from its reference:
While DirectoryStream
extends Iterable
, it is not a
general-purpose Iterable
as it supports only a single Iterator
;
invoking the iterator method to obtain a second or subsequent iterator
throws IllegalStateException
.
So the behaviour you see is to be expected. You should collect all your files to a single list. Something along these lines:
List<Path> jpegFilesList = new ArrayList<>();
while (Path p: jpegFiles)
jpegFilesList.add(p);
sortedJpegFiles = new String[jpegFilesList.size()];
for(Path jpegFile: jpegFilesList) {
…
}
Note that this issue about the IllegalStateException is rather distinct from the original question you asked. So it would be better off in a separate question. Remember that SO is not a forum. So please stick to one issue per question.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…