What I want to do is when I have a list of strings " insert "," create "," drop "`` `, I want to sort them in my favorite order instead of the natural order. Specifically, I want to sort in the order
" drop "," create "," insert "` ``.
In this case, since the elements of the set are limited, in SQL it is sufficient to sort by `` `case``` with the characteristic function. I want to do the same thing with java.
java 1.8
It has a characteristic function equivalent in Map
. key is an element of the set and value is an integer in the sort order.
Map<String, Integer> map = new HashMap<>();
map.put("drop", 1);
map.put("create", 2);
map.put("insert", 3);
List<String> list = Arrays.asList("insert", "create", "drop");
list.stream()
.sorted((s1, s2) -> map.get(s1).compareTo(map.get(s2)))
.forEach(System.out::println);
Output result.
drop
create
insert
The situation where this was needed was that I wanted to sort the files in a particular order. For example, suppose you have a group of files like this.
0001_create.sql
0001_drop.sql
0001_insert.sql
0002_create.sql
0002_drop.sql
0002_insert.sql
I wanted to get the file list in the order of prefix + suffix in the above-mentioned [drop-> create-> insert].
So the source code.
Map<String, Integer> map = new HashMap<>();
map.put("drop.sql", 1);
map.put("create.sql", 2);
map.put("insert.sql", 3);
Files.walk(Paths.get("files"))
.filter(Files::isRegularFile)
.sorted((p1, p2) -> {
String[] sp1 = p1.getFileName().toString().split("_");
String[] sp2 = p2.getFileName().toString().split("_");
String pp1 = sp1[0] + map.get(sp1[1]);
String pp2 = sp2[0] + map.get(sp2[1]);
return pp1.compareTo(pp2);})
.forEach(System.out::println);
Output result.
files\0001_drop.sql
files\0001_create.sql
files\0001_insert.sql
files\0002_drop.sql
files\0002_create.sql
files\0002_insert.sql
That doesn't change what you do. Separate the file names with a separator and convert the suffix part to an integer in the sort order with a characteristic function map. If you attach them in the order of prefix, you will get the strings `" 00013 "," 00012 "," 00011 "```, so all you have to do is
`compareTo```.
Recommended Posts