簡體   English   中英

在java中如何在列表中打印鍵值數組?

[英]In java how do i print key value array in list?

我正在嘗試使用java只使用arraylist創建一個簡單的電話簿

import java.util.*;

public class Lista {

    public static void menu() {
        int opcion = 0;
        String[] t2 = new String[2];
        ArrayList<String[]> lista = new ArrayList<String[]>();
        t2[0] = "Robert";
        t2[1] = "619-487-5555";
        lista.add(t2);

        t2 = new String[2]; // create a new array
        t2[0] = "Carlos";
        t2[1] = "123-659-8751";
        lista.add(t2);

        t2 = new String[2];
        t2[0] = "mike";
        t2[1] = "555-555-5555";
        lista.add(t2);
}
}

現在我如何才能訪問列表中的每個數組

name:mike

phone: 555-555-5555

我正計划建立一個菜單

/ *************** /

| 1 - 羅伯特|

| 1 - 卡洛斯|

| 1 - 邁克|

/ ********* /

當用戶輸入時,請說數字2,他將在屏幕上顯示相應的姓名和電話號碼。 這是一個控制台程序,只是為了說明列表的使用

你可以在你的情況下使用它。

for (String[] obj: lista)
{
    System.out.print("Name: ");
    System.out.println(obj[0]);

    System.out.print("Number: ");
    System.out.println(obj[1]);
}

你為什么不考慮使用地圖

例如

HashMap <String, String> map = new HashMap <> ();

然后加

map.put("mike", 911);

得到價值

System.out.println ("mikes number is " + map.get("mike"));

使用Map的另一個好處是可以防止你有重復的值(只有一個“mike”)

只需使用以下代碼 - :

for(String[] contact: lista) {
       System.out.println("name : "+contact[0]);
       System.out.println("phone : "+contact[1]);
}

您可以考慮使用HaspMap作為其他答案建議。

嘗試這個:

    Map<String, List<String>> phoneNumber = new LinkedHashMap<String, List<String>>();
    {
        List<String> phone = new ArrayList<String>();
        phone.add("619-487-5555");
        phone.add("619-487-5556");
        phone.add("619-487-5557");
        phoneNumber.put("Robert", phone);
    }
    {
        List<String> phone = new ArrayList<String>();
        phone.add("123-659-8751");
        phoneNumber.put("Carlos", phone);
    }
    {
        List<String> phone = new ArrayList<String>();
        phone.add("555-555-5555");
        phone.add("6666-555-5555");
        phoneNumber.put("mike", phone);
    }
    for (String person : phoneNumber.keySet()) {
        List<String> phoneList = phoneNumber.get(person);
        for (String phone : phoneList) {
            System.out.println("person: " + person + " | phone: " + phone);
        }
    }

控制台打印:

person: Robert | phone: 619-487-5555
person: Robert | phone: 619-487-5556
person: Robert | phone: 619-487-5557
person: Carlos | phone: 123-659-8751
person: mike | phone: 555-555-5555
person: mike | phone: 6666-555-5555

暫無
暫無

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

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