java8 按复数key将list排序
时间: 2024-05-10 21:20:23 浏览: 7
Java8中可以使用`Comparator`和`Map.Entry`来对具有复数键的`Map`进行排序,可以按照键的实部或虚部进行排序。
以下是一个示例代码:
```java
import java.util.*;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
Map<ComplexNumber, String> map = new HashMap<>();
map.put(new ComplexNumber(3, 2), "a");
map.put(new ComplexNumber(1, 4), "b");
map.put(new ComplexNumber(2, 3), "c");
// 按键的实部排序
List<Map.Entry<ComplexNumber, String>> entries1 = map.entrySet()
.stream()
.sorted(Comparator.comparing(e -> e.getKey().getReal()))
.collect(Collectors.toList());
// 按键的虚部排序
List<Map.Entry<ComplexNumber, String>> entries2 = map.entrySet()
.stream()
.sorted(Comparator.comparing(e -> e.getKey().getImaginary()))
.collect(Collectors.toList());
System.out.println("按键的实部排序:");
for (Map.Entry<ComplexNumber, String> entry : entries1) {
System.out.println("key=" + entry.getKey() + ", value=" + entry.getValue());
}
System.out.println("按键的虚部排序:");
for (Map.Entry<ComplexNumber, String> entry : entries2) {
System.out.println("key=" + entry.getKey() + ", value=" + entry.getValue());
}
}
}
class ComplexNumber {
private double real;
private double imaginary;
public ComplexNumber(double real, double imaginary) {
this.real = real;
this.imaginary = imaginary;
}
public double getReal() {
return real;
}
public void setReal(double real) {
this.real = real;
}
public double getImaginary() {
return imaginary;
}
public void setImaginary(double imaginary) {
this.imaginary = imaginary;
}
@Override
public String toString() {
return real + "+" + imaginary + "i";
}
}
```
输出结果:
```
按键的实部排序:
key=1.0+4.0i, value=b
key=2.0+3.0i, value=c
key=3.0+2.0i, value=a
按键的虚部排序:
key=3.0+2.0i, value=a
key=2.0+3.0i, value=c
key=1.0+4.0i, value=b
```