gpt4 book ai didi

java - 如何对列表中两个不同类的字段进行排序?

转载 作者:行者123 更新时间:2023-12-01 17:39:22 25 4
gpt4 key购买 nike

我有下面的代码,我需要根据不同类的字段对列表进行排序。

是否可以对不同类的字段数据进行排序并将其放入一个列表中?

import java.util.*;
import java.util.stream.Collectors;

public class Sample4 {

private class Student {
String name;
Set<Marks> marks;

}

private class Marks {
double points;
}

public static void main(String[] args) {
System.out.println(new Sample4().test());
}

public List<Marks> test() {
Set<Marks> marks = new LinkedHashSet<>(), marks1 = new LinkedHashSet<>(), marks2 = new LinkedHashSet<>();
marks.add(new Marks(10.2));
marks.add(new Marks(2.10));
marks1.add(new Marks(20));
marks1.add(new Marks(7));
marks2.add(new Marks(13));
marks2.add(new Marks(15));

List<Student> stds = Arrays.asList(
new Student("A", marks),
new Student("C", marks1),
new Student("B", marks2)
);

return stds.stream().sorted(Comparator.comparing(Student::getName)).flatMap(std -> std.getMarks().stream()).sorted(Comparator.comparing(Marks::getPoints)).collect(Collectors.toList());
}
}

请查找上面的代码以供引用。但我正在寻找的输出如下:

A -> 2.10, 10.2

B -> 13, 15

C -> 7, 20

最佳答案

如果您想要包含学生姓名 A 之间的链接的输出以及诸如 2.10 之类的标记和10.2 ,那么您需要 Map<String, List<Mark>>输出或使用当前List<Student这只是根据您的需要进行排序的:

输出为List<Student> :

return stds.stream()
.sorted(Comparator.comparing(Student::getName)) // sort Students by name
.map(student -> new Student( // with sorted marks
student.getName(), // - same name
student.getMarks().stream() // - sorted marks
.sorted(Comparator.comparingDouble(Marks::getPoints)) // -- comparing points
.collect(Collectors.toCollection(LinkedHashSet::new)))) // -- as LinkedHashSet
.collect(Collectors.toList()); // as List<Student>

[Student(name=A, marks=[Marks(points=2.1), Marks(points=10.2)]),

Student(name=B, marks=[Fooarks(points=13.0), Marks(points=15.0)]),

Student(name=C, marks=[Marks(points=7.0), Marks(points=20.0)])]

<小时/>

如果你找到Map<String, List<Mark>>不知何故更合适,然后介意 TreeMap对键进行排序的实现:

return stds.stream()
.collect(Collectors.toMap( // Map<String, List>
Student::getName, // the key
student -> student.getMarks().stream() // the value (sorted)
.sorted(Comparator.comparingDouble(
Marks::getPoints))
.collect(Collectors.toList()),
(o1, o2) -> o1, // merge BinaryOperator
TreeMap::new)); // requested implementation

{A=[Foo.Marks(points=2.1), Foo.Marks(points=10.2)],

B=[Foo.Marks(points=13.0), Foo.Marks(points=15.0)],

C=[Foo.Marks(points=7.0), Foo.Marks(points=20.0)]}

关于java - 如何对列表中两个不同类的字段进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60988625/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com