我正在编写自定义差异软件,我需要有关自定义比较器的帮助。 所以我没有比较器的输出是: 第一个例子:
{
chars1: [a, b, c]
numbers1: [1, 2, 3, 4]
+ chars2: false
+ checked: true
+ default: [value1, value2]
+ id: null
+ key2: value2
+ numbers2: [22, 33, 44, 55]
+ numbers4: [4, 5, 6]
+ obj1: {nestedKey=value, isNested=true}
+ setting1: Another value
+ setting2: 300
+ setting3: none
- chars2: [d, e, f]
- checked: false
- default: null
- id: 45
- key1: value1
- numbers2: [2, 3, 4, 5]
- numbers3: [3, 4, 5]
- setting1: Some value
- setting2: 200
- setting3: true
}
第二个例子:
{
host: hexlet.io,
+ timeout: 20,
+ verbose: true,
- follow: false,
- proxy: 123.234.53.22,
- timeout: 50
}
它必须按字母顺序排序,如下所示:
第一次排序:
{
chars1: [a, b, c]
- chars2: [d, e, f]
+ chars2: false
- checked: false
+ checked: true
- default: null
+ default: [value1, value2]
- id: 45
+ id: null
- key1: value1
+ key2: value2
numbers1: [1, 2, 3, 4]
- numbers2: [2, 3, 4, 5]
+ numbers2: [22, 33, 44, 55]
- numbers3: [3, 4, 5]
+ numbers4: [4, 5, 6]
+ obj1: {nestedKey=value, isNested=true}
- setting1: Some value
+ setting1: Another value
- setting2: 200
+ setting2: 300
- setting3: true
+ setting3: none
}
第二次排序:
{
- follow: false
host: hexlet.io
- proxy: 123.234.53.22
- timeout: 50
+ timeout: 20
+ verbose: true
}
一旦我得到看起来像这样的比较器:
Comparator.comparing((String str) -> str.startsWith(plusPrefix) ? 1 : -1)
.thenComparing(str -> str.substring(plusPrefix.length()))
但它不适用于我的新示例,您可以在上面看到。有人可以帮助我改进我的比较器以处理这两个示例吗? 顺便说一句:我在这个例子中使用 TreeMap 对它们进行排序,但是在此之后我将它们放入 StringBuilder,因为我的输出必须在 String 中(也许这会有所帮助:P)
使用另一个比较器进行采样
Comparator.comparing((String str) -> str.substring(1))
.thenComparingInt(str -> " -+".indexOf(str.charAt(0)))
{
chars1: [a, b, c]
numbers1: [1, 2, 3, 4]
+ chars2: false
+ checked: true
+ default: [value1, value2]
+ id: null
+ key2: value2
+ numbers2: [22, 33, 44, 55]
+ numbers4: [4, 5, 6]
+ obj1: {nestedKey=value, isNested=true}
+ setting1: Another value
+ setting2: 300
+ setting3: none
- chars2: [d, e, f]
- checked: false
- default: null
- id: 45
- key1: value1
- numbers2: [2, 3, 4, 5]
- numbers3: [3, 4, 5]
- setting1: Some value
- setting2: 200
- setting3: true
}
答案 0 :(得分:1)
尝试以下操作:
Comparator.comparing((String str) -> str.substring(1))
.thenComparingInt(str -> " -+".indexOf(str.charAt(0)))