logo

מפה של מפה ב-Java

ב-Java, מַפָּה הוא ממשק שממפה מפתחות לערכים. לפעמים זה נדרש ליישם מפה של מפה (מפה מקוננת).

bash לשרשור מחרוזות

מפה מקוננת משמש במקרים רבים, כגון אחסון שמות התלמידים עם המזהים שלהם של קורסים שונים. במקרה זה, אנו יוצרים מפה בעלת מפתח, כלומר, שם וערך של הקורס, כלומר, מפה אחרת בעלת מפתח, כלומר, מזהה וערך, כלומר, שם התלמיד.

עלינו להשתמש בשלבים הבאים כדי ליצור מפת מפה ב-Java:

משחקי imessage עם אנדרואיד
  1. קח את המספר הכולל של תלמידים מהמשתמש עבור כל קורס.
  2. מלא את פרטי התלמיד של כל הקורסים על ידי קבלת קלט מהמשתמש.
  3. מלא את המפה הראשית על ידי הוספת שם הקורס כמפתח ומפה במילוי משתמש כערך.
  4. ב-for loop, אנו ממירים תחילה את כל המפתחות של המפה ל-ArrayList מסוג Object.
  5. לאחר מכן, אנו מקבלים את האובייקט מהרשימה על ידי שימוש בשיטת get() ומקבלים ערך מהמפה המקבילה לאובייקט זה לערך הדפסה.

בואו ליישם את ההיגיון ליצירת Map of Map לאחסון נתונים.

MapOfMapExample.java

 import java.util.HashMap; import java.util.Map; import java.util.*; //create class MapOfMapExample to create a MapOfMap Example public class MapOfMapExample { // main() method start public static void main(String[] args) { // declare variables int size1 = 0; int size2 = 0; // create a Map for BCA students that will store students Id and Name Map bcaStudents = new HashMap(); // create a Map for MCA students that will store students Id and Name Map mcaStudents = new HashMap(); // create Scanner class object to take input from user Scanner sc = new Scanner(System.in); System.out.println(&apos;Enter total number of BCA students.&apos;); size1 = Integer.parseInt(sc.nextLine()); System.out.println(&apos;Enter total number of MCA students.&apos;); size2 = Integer.parseInt(sc.nextLine()); // fill bcaStudents Map by taking input from user for(int i = 1; i <= size1; i++){ int id="100;" string name ; system.out.println('enter of ' + i 'st student bca:'); system.out.println('student '; mca:'); bca', bcastudents); students.put('mca', mcastudents); print students map system.out.println('map map: students); elements for (int < students.size(); arraylist data="new" arraylist(students.keyset()); object obj="data.get(i);" system.out.println('course: students: students.get(obj)); } close scanner class sc.close(); pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/java-tutorial/96/map-map-java.webp" alt="Map of Map in Java"> <hr></=>