亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Java - 在迭代對象列表時搜索特定屬性

Java - 在迭代對象列表時搜索特定屬性

青春有我 2021-11-24 15:29:38
我正在努力尋找相關的答案來解決我的問題。我有一個數組列表:List<Teacher> teacherList = new ArrayList<Teacher>(11);教師類有一個 name 屬性。我想掃描教師列表,并找出是否有與用戶輸入的名稱匹配的名稱。例如,Scanner teacherNameScanner = new Scanner (System.in);System.out.println("What is the teachers name");teacherName = teacherNameScanner.nextLine();/* Here I want to scan through the teacherList and see whether the name enteredmatches the name of any of the teachers. If it does not match I want to tell theuser to enter a correct name */
查看完整描述

3 回答

?
海綿寶寶撒

TA貢獻1809條經驗 獲得超8個贊

在Java8 中,您可以使用流:


public static Teacher findByName(Collection<Teacher> teachers, String name) {

    return teachers.stream().filter(teacher -> teacher.getName().equals(name)).findFirst().orElse(null);

}

此外,如果您有許多不同的對象(不僅是Teacher),或者您想通過不同的屬性(不僅是name)找到它,您可以構建一個實用程序類,以在其中封裝此邏輯:


public final class FindUtils {

    public static <T> T findByProperty(Collection<T> col, Predicate<T> filter) {

        return col.stream().filter(filter).findFirst().orElse(null);

    }

}


public final class TeacherUtils {

    public static Teacher findByName(Collection<Teacher> teachers, String name) {

        return FindUtils.findByProperty(teachers, teacher -> teacher.getName().equals(name));

    }


    public static Teacher findByAge(Collection<Teacher> teachers, int age) {

        return FindUtils.findByProperty(teachers, teacher -> teacher.getAge() == age);

    }


}


查看完整回答
反對 回復 2021-11-24
?
慕容森

TA貢獻1853條經驗 獲得超18個贊

這真的取決于您的用例,名稱是否區分大小寫?此外,您可能需要考慮修剪空間。然后創建一個 Set nameSet,您可以在其中對現有名稱進行獲取,這是一個 O(1) 操作。同樣,對此有許多解決方案,除非您描述確切的用例,例如您想用姓名還是 ID(通常是 ID)來識別教師,否則很難想出正確的解決方案。但是根據您所描述的 HashSet 應該可以。


Set<String> nameSet = new HashSet<String>();


if (nameSet.contains(teacherName))

   do what you want

else

   other case


查看完整回答
反對 回復 2021-11-24
?
慕桂英4014372

TA貢獻1871條經驗 獲得超13個贊

要掃描teacherList并查找輸入的教師姓名 ( teacherName)是否匹配,可以使用以下方法之一。請注意,每個方法都將 theteacherList和 theenteredName作為參數并返回booleantrue 或 false - 取決于是否找到匹配項。


共有三種方法,每種方法的表現各不相同。請注意第三個構造 C - 這使用了與前兩個不同的方法 - A 和 B。



方法一:


teacherList使用 for 循環迭代并查找是否有匹配名稱的老師:


for (Teacher teacher : teacherList) {

    if (teacher.getName().equals(enteredName)) {

        // a match is found

        return true;

    }

}


return false;


方法B:


這與方法 A 具有相同的功能,但使用不同的代碼構造 - 流和 lambda:


boolean enteredTeacherExists =  teacherList.stream()

                                           .anyMatch(teacher -> teacher.getName().equals(enteredName));

語法teacher -> teacher.getName().equals(enteredName)是一個類型為 的 lambda 表達式Predicate<Teacher>。



方法C:


此方法使用不同的方法。不是測試教師的姓名 - 使用輸入的姓名構造教師對象,該對象用于查找匹配項。


根據輸入的名字創建一個教師,并測試它是否存在于列表中。


Teacher enteredTeacher = new Teacher(enteredName);

boolean enteredTeacherExists = teacherList.contains(enteredTeacher);

如果列表中存在同名教師,則返回值為真,否則為假。


請注意Teacher該類(參見下面的定義)有一個java.lang.Object類的重寫equals()方法。此方法指定兩個教師對象相等的標準 - 如果它們的名稱相等,則教師對象被視為相等。這允許使用 equalsList的contains方法。



編碼:


老師.java:


public class Teacher {


    private String name;


    public Teacher(String name) {

        this.name = name;

    }


    public String getName() {

        return name;

    }


    @Override

    /* This returns a string representation of the teacher - the name. */

    public String toString() {

        return name;

    }


    @Override

    public boolean equals(Object other) {

        if ((other != null) && (other instanceof Teacher)) {

            Teacher otherTeacher = (Teacher) other;

            if (otherTeacher.getName().equals(this.name)) {

                return true;

            }

        }

        return false;

    }

}


教師測試器.java


public class TeacherTester {


    public static void main(String [] args) {


        // Create some teachers

        Teacher teacher1 = new Teacher("first");

        Teacher teacher2 = new Teacher("second");

        Teacher teacher3 = new Teacher("third");

        List<Teacher> teacherList = Arrays.asList(teacher1, teacher2, teacher3);


        System.out.println("Teachers: " + teacherList);


        // Look for teacher - using method A

        String enteredName = "ninth";

        System.out.println("A. Found " + enteredName + " : " + findTeacherA(teacherList, enteredName));

        enteredName = "first";

        System.out.println("A. Found " + enteredName + " : " + findTeacherA(teacherList, enteredName));


        // Look for teacher - using method B

        enteredName = "ninth";

        System.out.println("B. Found " + enteredName + " : " + findTeacherB(teacherList, enteredName));

        enteredName = "second";

        System.out.println("B. Found " + enteredName + " : " + findTeacherB(teacherList, enteredName));


        // Look for teacher - using method C

        enteredName = "third";

        System.out.println("C. Found " + enteredName + " : " + findTeacherC(teacherList, enteredName));

        enteredName = "ninth";

        System.out.println("C. Found " + enteredName + " : " + findTeacherC(teacherList, enteredName));     


    }


    private static boolean findTeacherA(List<Teacher> teacherList, String enteredName) {


        for (Teacher teacher : teacherList) {


            if (teacher.getName().equals(enteredName)) {

                // a match is found

                return true;

            }

        }


        return false;

    }


    private static boolean findTeacherB(List<Teacher> teacherList, String enteredName) {


        return teacherList.stream()

                            .anyMatch(teacher -> teacher.getName().equals(enteredName));

    }


    private static boolean findTeacherC(List<Teacher> teacherList, String enteredName) {


        Teacher enteredTeacher = new Teacher(enteredName);

        return teacherList.contains(enteredTeacher);

    }

}


輸出:


Teachers: [first, second, third]

A. Found ninth : false

A. Found first : true

B. Found ninth : false

B. Found second : true

C. Found third : true

C. Found ninth : false


查看完整回答
反對 回復 2021-11-24
  • 3 回答
  • 0 關注
  • 202 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號