簡體   English   中英

使用Lambda表達式將列表轉換為地圖不起作用

[英]Converting List to Map using Lambda Expression Not working

我試圖將一個Student對象列表轉換成一個映射,其中鍵是整數(即Student對象的rollno字段),而Value是Student對象本身。

以下是我編寫的代碼:

package fibonacci;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class MApfor {


    public static void main(String[] args) {


        List<Student> maplist=new ArrayList<>();

        maplist.add(new Student(1, "pavan"));
        maplist.add(new Student(2, "Dhoni"));
        maplist.add(new Student(3, "kohli"));

        maplist.forEach(System.out::println);

        Map<Integer,Student> IS=new HashMap<>();



        IS = maplist.stream().collect(Collectors.toMap(a -> a.getRollNo,a);



    }
}

每當我嘗試寫最后一行時,即

IS = maplist.stream().collect(Collectors.toMap(a -> a.getRollNo,a);

我無法檢索rollNo字段,eclipse沒有顯示建議,即每當我鍵入a.get來將rollNo分配給鍵時,我都無法這樣做。

請提出我面臨的問題。

package fibonacci;

public class Student {


    public int rollNo;
    public String name;
    public int getRollNo() {
        return rollNo;
    }
    public void setRollNo(int rollNo) {
        this.rollNo = rollNo;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Student(int rollNo, String name) {
        super();
        this.rollNo = rollNo;
        this.name = name;
    }
    @Override
    public String toString() {
        return " [rollNo=" + rollNo + ", name=" + name + "]";
    }

}

應該是這樣

maplist.stream().collect(Collectors.toMap(a -> a.rollNo, Function.identity()));

甚至更好的方法是將getter與方法引用一起使用。

maplist.stream().collect(Collectors.toMap(Student::getRollNo, Function.identity()));

a -> a.getRollNo這是不正確的。 您應該使用公共場所或吸氣劑。 您沒有正確使用兩者。

當您說a.getRollNo ,這意味着您的類中應該有一個名為getRollNo的公共字段,這是不正確的。 您的字段稱為rollNo。
然后,如果要訪問rollNo的getter方法,則它應該類似於a.getRollNo()。 (您最后缺少() )。
但是您也可以使用類似方法的引用Student::getRollNo

所以應該是其中之一

a -> a.rollNo
a -> a.getRollNo()
Student::getRollNo

您也可以用a -> a替換Function.identity()

  • a.getRollNo不存在,適當的吸氣劑a.getRollNo()a.rollNo直接,但你最好設置你的會員為private
  • 您必須使用a -> a函數,將對象映射到自身
IS = maplist.stream().collect(Collectors.toMap(a -> a.getRollNo(), a -> a));
// or
IS = maplist.stream().collect(Collectors.toMap(a -> a.getRollNo(), Function.identity());

使用方法參考

IS = maplist.stream().collect(Collectors.toMap(Student::getRollNo, Function.identity()));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM