2014-09-17 4 views
1

Я хотел бы спросить, можно ли распечатать мой arraylist с помощью map.get().get()? Вывод должен быть:Получение ArrayList

"Aguinaldo, Marcos, Quezon" 

И способ печати должно быть: System.out.println(map.get("Philippines").get("President")); Я не получал никаких проблем с другим выходом, кроме как на этом.

Вот код для моего главный:

import java.util.*; 

public class PresMain{ 

public static void main(String args[]){ 



HashMap<String, HashMap<String, Object>> map = new HashMap<String, HashMap<String, Object>>(); 
map.put("Philippines", new HashMap<String, Object>()); 
map.get("Philippines").put("capital", "Manila"); 
map.get("Philippines").put("continent", "Asia"); 


System.out.println(map.get("Philippines").get("capital")); 
System.out.println(map.get("Philippines").get("continent")); 


List<President> list = new ArrayList<President>(); 

list.add(new President("Aguinaldo", 1)); 
list.add(new President("Marcos", 10)); 
list.add(new President("Quezon", 2)); 

Collections.sort(list); 
for(President a: list) 
System.out.print(a.getPresName() + ", "); 


Collections.sort(list, new President()); 

System.out.println(" "); 
for(President a: list) 
System.out.println(a.getPresName() +" , "+ a.getPresYear()); 

} 
} 

Извините за не включая мой другой класс некоторое время назад, так вот она:

enter code here 
import java.util.*; 

class President implements Comparator<President>, Comparable<President>{ 
private String name; 
private int year; 
int x; 

President(){ 

} 

President(String n, int a){ 
    name = n; 
    year = a; 


} 

public String getPresName(){ 
    return name; 
} 

public int getPresYear(){ 
    return year; 
} 

public int getPresX(){ 
return x; 
} 

// Overriding the compareTo method; sort(list) 
public int compareTo(President d){ 
    //return (this.name).compareTo(d.name); 
    return this.year - d.year; 
} 

// Overriding the compare method to sort the age 
public int compare(President d, President d1){ 
//return (d.name).compareTo(d1.name); 
// return d.age - d1.age; 
return d.x - d1.x; 
} 
} 
+6

'Collections.sort (список, новый президент());' ??. Ваш 'Президент' реализует' Компаратор'? – TheLostMind

+0

Вам нужно вывести его отсортированным? У вас проблемы с отправкой на выход? Отсортировано на основе чего? –

+0

Мои результаты должны быть: Manila Asia Агуинальдо, 1 Кесон, 2 Marcos, 10 Я должен также быть в состоянии напечатать: Aguinaldo, Маркос, Кесон –

ответ

0

Я хотел бы попробовать что-то вроде:

public class PresMain{ 

public static void main(String args[]){ 



HashMap<String, HashMap<String, Object>> map = new HashMap<String, HashMap<String, Object>>(); 
map.put("Philippines", new HashMap<String, Object>()); 
map.get("Philippines").put("capital", "Manila"); 
map.get("Philippines").put("continent", "Asia"); 


System.out.println(map.get("Philippines").get("capital")); 
System.out.println(map.get("Philippines").get("continent")); 


List<President> list = new ArrayList<President>(); 

list.add(new President("Aguinaldo", 1)); 
list.add(new President("Marcos", 10)); 
list.add(new President("Quezon", 2)); 

//Don't know why you're doing this, have to sort them? Then President class needs to implement Comparator Interface. 
//Collections.sort(list); 
//for(President a: list) 
// System.out.print(a.getPresName() + ", "); 

//Collections.sort(list, new President()); 
//System.out.println(" "); 
//for(President a: list) 
// System.out.println(a.getPresName() +" , "+ a.getPresYear()); 
// } 

map.get("Philippines".put("president", list); 
//To get this working you may override the toString method in your presidents list. 
System.out.println(map.get("Philippines").get("president").toString()); 

} 

Закрыть, что вы ищете?

0

Эта линия не должна работать даже:

Collections.sort(list, new President()); 

Если что-нибудь, President должен либо реализовать Comparable<T>

http://docs.oracle.com/javase/8/docs/api/java/lang/Comparable.html

How to implement the Java comparable interface?

или вы должны дать ему Comparator<T> реализацию, как так:

http://docs.oracle.com/javase/8/docs/api/java/util/Comparator.html

How to use Comparator in Java to sort

Затем код должен работать, как задумано.

0

Если вы хотите напечатать имена президентов и президент лет отсортирован:

List<President> list = new ArrayList<President>(); 

list.add(new President("Aguinaldo", 1)); 
list.add(new President("Marcos", 10)); 
list.add(new President("Quezon", 2)); 

Collections.sort(list, new President()); 

map.get("Philippines").put("presidents", list); 

for(Entry<String, HashMap<String, Object>> entry: map.getEntrySet()){ 
    HasMap<String, Object> attributes = entry.getValue(); 
    List<President> pList = (List<President>) attributes.get("presidents"); 
    for(President p: pList) System.out.print(p.getPresName() + ", " + p.getYear() + " "); 
} 

Выход:

"Aguinaldo, 1 Quezon, 2 Marcos, 10" 

Вы должны сделать проверку, чтобы убедиться, что вы не получаете NPE (например, всегда есть ключ «президентов» и т. д.).

Таким образом, у вас есть Map, который содержит Map, который содержит List. Это немного грязно. Почему бы вам не использовать классы Java?

public class State{ 
    String name; 
    String capital; 
    List<President> presidents; 

    public State(String name){ 
     this.name = name; 
    } 
    public String getName() { 
     return name; 
    } 
    public void setName(String name) { 
     this.name = name; 
    } 
    public String getCapital() { 
     return capital; 
    } 
    public void setCapital(String capital) { 
     this.capital = capital; 
    } 
    public List<String> getPresidents() { 
     return presidents; 
    } 
} 

В ваш главный:

State philippines = new State("Philippines"); 
philippines.setCapital("Manila"); 
philippines.getPresidents().add(new President("Aguinaldo", 1)); 
philippines.getPresidents().add(new President("Marcos", 10)); 
philippines.getPresidents().add(new President("Quezon", 2)); 

Collections.sort(philippines.getPresidents(), new President());  

for(President p: philippines.getPresidents()) 
    System.out.print(p.getPresName()); 

И хранить ваши состояния:

Map<String, State> states = new HashMap<String, State>(); 
//create philippines 
states.add("Philippines", philippines); 

Collections.sort(states.get("Philippines").getPresidents(), new President()); 

for(President p: states.get("Philippines").getPresidents()) 
    System.out.print(p.getPresName()); 
Смежные вопросы