【问题标题】:How to transpose the list in java如何在java中转置列表
【发布时间】:2016-01-18 03:51:00
【问题描述】:

我想转置我的列表

假设我有 studentList

List<Student> studentList = new ArrayList<Student>();
studentList.add(new Student(101, "English", "95"));
studentList.add(new Student(101, "Maths", "82"));
studentList.add(new Student(101, "Biology", "93"));
studentList.add(new Student(101, "Physics", "77"));
studentList.add(new Student(101, "Chemistry", "65"));
studentList.add(new Student(102, "English", "86"));
studentList.add(new Student(102, "Maths", "75"));
studentList.add(new Student(102, "Biology", "68"));
studentList.add(new Student(102, "Physics", "63"));
studentList.add(new Student(102, "Chemistry", "84"));
studentList.add(new Student(103, "English", "92"));
studentList.add(new Student(103, "Maths", "88"));
studentList.add(new Student(103, "Biology", "67"));
studentList.add(new Student(103, "Physics", "81"));
studentList.add(new Student(103, "Chemistry", "93"));

public class Student {

    private Integer rollNo;

    private String subject;

    private String marks;

..........
}

我想将此数据转置到 StudentResultList

List<StudentResult> studentResultList = new ArrayList<StudentResult>();


public class StudentResult {

    private String rollno;

    private String english;

    private String maths;

    private String biology;

    private String physics;

    private String chemistry;

..........

}

预期输出:

            101         102         103

English     95          86          92

Maths       82          75          88

Biology     93          68          67  

Physics     77          63          81  

Chemistry   65          84          93  

我必须使用什么集合来转置我的列表?

我尝试使用

进行转换

HashMap&lt;Integer,Object&gt; (Integer 是 RollNo,Object 是另一个 hashmap)

HashMap&lt;String, String&gt; (字符串是主题,另一个字符串是标记)

使用这个我将学生列表转换为学生结果列表。

有人建议我,有没有更好的方法来转置列表?

【问题讨论】:

  • 为什么需要这些额外的对象?为什么你不能直接遍历学生并将它们添加到学生结果中?
  • @ergonaut 在 Studentclass 英语、物理等中是主题字段的值。在 StudentResult 类中,它们是字段。我们不能直接迭代student类并添加到studentresult类中

标签: java arraylist data-structures collections


【解决方案1】:

没有隐式/自动的方法可以做到这一点。

您必须坐下来写下迭代 studentList 的代码,并收集构建另一个列表所需的信息。

记住:基本上你有两个对象;一个代表Student类的对象;另一个保存 StudentResult 类的对象。但是计算机不知道应该收集一类的哪些属性来构建第二类的对象——除非你坐下来提供这些信息。

换句话说:如果您要查看数据库,您将能够运行查询和其他操作来为您的数据构建不同的视图。但是没有数据库,所以在现有数据上构建不同视图的所有逻辑......必须手动编程。

【讨论】:

  • 我尝试使用 HashMap 进行转换(Integer 是 RollNo,Object 是另一个 hashmap) HashMap (String 是 Subject 而另一个 String 是 Marks)...这是正确的方式
  • 我刚刚告诉过您:您不能简单地将您的列表转换为其他集合:您必须根据只能通过手动迭代第一个列表来检索的数据来构建新列表。
猜你喜欢
  • 1970-01-01
  • 2022-12-11
  • 2016-05-17
  • 2017-08-14
  • 2018-08-29
  • 2018-10-23
  • 1970-01-01
  • 2014-11-07
  • 2011-09-27
相关资源
最近更新 更多