假设有两个List:
一个存放了五个User对象,含有id,名称之类的属性;
另一个存放了四个连线关系,fromId 和 toId,这两个值取的都是user的id
A-->B-->C-->D-->E
如何能给这五个对象排序出来!!
如何通过连线对对象排序!
- 写回答
- 好问题 0 提建议
- 追加酬金
- 关注问题
- 邀请回答
-
1条回答 默认 最新
关注 可以使用拓扑排序
import java.util.*; // User class class User { int id; String name; public User(int id, String name) { this.id = id; this.name = name; } } // Edge class class Edge { int fromId; int toId; public Edge(int fromId, int toId) { this.fromId = fromId; this.toId = toId; } } public class Main { public static void main(String[] args) { List<User> users = Arrays.asList( new User(1, "A"), new User(2, "B"), new User(3, "C"), new User(4, "D"), new User(5, "E") ); List<Edge> edges = Arrays.asList( new Edge(1, 2), new Edge(2, 3), new Edge(3, 4), new Edge(4, 5) ); List<User> sortedUsers = topologicalSort(users, edges); System.out.println(sortedUsers); } public static List<User> topologicalSort(List<User> users, List<Edge> edges) { Map<Integer, List<Integer>> graph = new HashMap<>(); for (Edge edge : edges) { graph.computeIfAbsent(edge.fromId, x -> new ArrayList<>()).add(edge.toId); } List<User> sortedUsers = new ArrayList<>(); Set<Integer> visited = new HashSet<>(); for (User user : users) { topologicalSortUtil(graph, user.id, visited, sortedUsers); } return sortedUsers; } private static void topologicalSortUtil(Map<Integer, List<Integer>> graph, int v, Set<Integer> visited, List<User> sortedUsers) { if (visited.contains(v)) { return; } visited.add(v);
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报
悬赏问题
- ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
- ¥15 Python3.5 相关代码写作
- ¥20 测距传感器数据手册i2c
- ¥15 RPA正常跑,cmd输入cookies跑不出来
- ¥15 求帮我调试一下freefem代码
- ¥15 matlab代码解决,怎么运行
- ¥15 R语言Rstudio突然无法启动
- ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
- ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
- ¥15 用windows做服务的同志有吗