如果我有ArrayList,如何比较两个HashMap?

时间:2019-02-12 19:02:55

标签: java string arraylist hashmap compare

我无法继续我的HashMap家庭作业。你能帮我吗?

我有2个HashMapmtutorsmstudents

mtutors键:他们的名字。
mtutors值:主题。
mstudents键:他们的名字。
mstudents值:subject(ArrayList

我必须找到匹配的导师学生。 例如: mtutors键之一:Peter Parker。 mtutors值之一:数学。 mstudents密钥之一:Bill Gates。 mstudents值之一:math,IT。 配对:Peter Parker和Bill Gates-数学。

HashMap<String,String> mtutors = new HashMap<>();
HashMap<String,ArrayList> mstudents = new HashMap<>();
for(int i=0;i<tutors.size();i++)
    mtutors.put(tutors.get(i).firstName + " " 
          + tutors.get(i).lastName, tutors.get(i).subject);
for(int i=0;i<students.size();i++)
    mstudents.put(students.get(i).firstName + " " 
          + students.get(i).lastName, students.get(i).students);

3 个答案:

答案 0 :(得分:2)

如果您使用的是Java8或更高版本,请尝试以下操作:

mtutors.forEach((tutorName, subject) -> {
        mstudents.forEach((studentName, subjects) -> {
            if (subjects.contains(subject)) {
                System.out.println(tutorName + ":" + studentName + ":" + subject);
            }
        });
    });

我假设您正在将科目(而非学生)放置在学生地图上。

示例数据流仅用于首次拟合。

mtutors.forEach((tutorName, subject) -> {
        mstudents.entrySet().stream()
                .filter(entry -> entry.getValue().contains(subject))
                .findFirst()
                .ifPresent(entry -> System.out.println(tutorName + ":" + entry.getKey() + ":" + subject));
    });

答案 1 :(得分:1)

我的答案类似于@ŁukaszKucik答案,只是Java流。 您可能不应该将我的解决方案用于作业,因为我猜这不是您应该解决的方式。尽管如此,只是为了多样化:

List<String> matches = mtutors.entrySet()
                .stream()
                .flatMap(tutor -> mstudents.entrySet()
                        .stream()
                        .filter(student -> student.getValue()
                                .contains(tutor.getValue()))
                        .map(student -> tutor.getKey() + " and " + student.getKey() + " - " + tutor.getValue()))
                .collect(Collectors.toList());

如果丢失的部分是list.contains()https://www.tutorialspoint.com/java/util/arraylist_contains.htm

如果您缺少的部分是一般如何解决这种组合的问题,那么这里只是要求解决方案不是学习和作业的工作原理。

答案 2 :(得分:0)

两个解决方案示例:

  1. forEach Lambda-Java 8或更高版本
  2. 经典for循环

对未来的建议

a。不要直接使用类变量-而是根据Java Bean规范创建getter / setter对。然后使用它们:例如相反,tutors.get(i).lastName使用tutors.get(i).getLastName()

b。在编写for循环时,即使只有一行,也要使用大括号-这可以防止循环体意外输入错误。例如

for (int i = 0; i < students.size(); i++) {
        mstudents.put(students.get(i).getFirstName() + " " + students.get(i).getLastName(), students.get(i).getSubjects());
    }

代替

for (int i = 0; i < students.size(); i++)
        mstudents.put(students.get(i).firstName + " " + students.get(i).lastName, students.get(i).subjects);

=====================

package org.tempuri.tests;

import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map.Entry;

public class SimpleTest {

  public static void main(String[] args) {

    // Just for test - inbound data
    Tutor mathTutor = new Tutor("Peter", "Parker", "MATH");
    Tutor physicsTutor = new Tutor("Tonny", "Stark", "PHYSICS");
    Tutor computersTutor = new Tutor("Steve", "Rogers", "COMPUTERS");

    Student freshmen = new Student("Bill", "Gates", Arrays.asList("MATH", "COMPUTERS"));
    Student sophomore = new Student("Peter", "Quill", Arrays.asList("MATH", "COMPUTERS", "PHYSICS"));
    Student senior = new Student("Peggy", "Carter", Arrays.asList("MATH", "PHYSICS"));

    List<Tutor> tutors = Arrays.asList(mathTutor, physicsTutor, computersTutor);
    List<Student> students = Arrays.asList(freshmen, sophomore, senior);

    // Untouched question code (almost ...)
    HashMap<String, String> mtutors = new HashMap<>();
    HashMap<String, List<String>> mstudents = new HashMap<>();
    for (int i = 0; i < tutors.size(); i++)
        mtutors.put(tutors.get(i).firstName + " " + tutors.get(i).lastName, tutors.get(i).subject);

    for (int i = 0; i < students.size(); i++)
        mstudents.put(students.get(i).firstName + " " + students.get(i).lastName, students.get(i).subjects);

    // variation 1. using forEach Lambda (> Java 8)
    List<MatchingPair> matchingPairs1 = new LinkedList<>();

    mtutors.entrySet().forEach(tutorEntry -> {

        mstudents.entrySet().forEach(studentEntry -> {
            if (studentEntry.getValue().contains(tutorEntry.getValue()))
                matchingPairs1
                        .add(new MatchingPair(tutorEntry.getKey(), studentEntry.getKey(), tutorEntry.getValue()));
        });

    });

    System.out.println("result variation1: ");
    System.out.println("------------------ ");

    matchingPairs1.forEach(onePair -> System.out.println("Tutor: " + onePair.getTutorName() + " -> Student: "
            + onePair.getStudentName() + " -> Subject: " + onePair.getSubject()));

    // variation 2. using classical for loops (< Java 7)
    final List<MatchingPair> matchingPairs2 = new LinkedList<>();

    for (Entry<String, String> oneTutor : mtutors.entrySet()) {
        for (Entry<String, List<String>> oneStudent : mstudents.entrySet()) {

            if (oneStudent.getValue().contains(oneTutor.getValue())) {
                matchingPairs2.add(new MatchingPair(oneTutor.getKey(), oneStudent.getKey(), oneTutor.getValue()));
            }
        }
    }
    System.out.println("------------------ ");
    System.out.println();
    System.out.println("result variation2: ");
    System.out.println("------------------ ");

    for (MatchingPair onePair : matchingPairs2) {
        System.out.println("Tutor: " + onePair.getTutorName() + " -> Student: " + onePair.getStudentName() + " -> Subject: "
                + onePair.getSubject());
    }
    System.out.println("------------------ ");
}


    // supporting classes for test
private static class MatchingPair {

    private String tutorName;
    private String studentName;
    private String subject;

    MatchingPair(String tutorName, String studentName, String subject) {
        this.tutorName = tutorName;
        this.studentName = studentName;
        this.subject = subject;
    }

    public String getTutorName() {
        return tutorName;
    }

    public void setTutorName(String tutorName) {
        this.tutorName = tutorName;
    }

}

private static class Tutor {

    String firstName;
    String lastName;
    String subject;

    Tutor(String firstName, String lastName, String subject) {

        this.firstName = firstName;
        this.lastName = lastName;
        this.subject = subject;

    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getSubject() {
        return subject;
    }

    public void setSubject(String subject) {
        this.subject = subject;
    }

}

private static class Student {

    String firstName;
    String lastName;
    List<String> subjects;

    Student(String firstName, String lastName, List<String> subjects) {

        this.firstName = firstName;
        this.lastName = lastName;
        this.subjects = subjects;

    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public List<String> getSubjects() {
        return subjects;
    }

    public void setSubjects(List<String> subjects) {
        this.subjects = subjects;
    }

}
}