「Java」HashMap>のサンプルプログラム

サンプルコード下記:

package namespace;
import java.util.*;
class Student implements Comparable<Student>
{
private String id;
public String name;
public Student(String id,String name)
{
this.id=id;
this.name=name;
}
public String getName()
{
return this.name;
}
public String getId()
{
return this.id;
}
public int hashCode()
{
return this.name.hashCode()+this.id.hashCode();
}
public boolean equals(Object obj)
{
Student student=(Student)obj;
return this.name.equals(student.name) && this.id.equals(student.id);
}
public int compareTo(Student stu)
{
int num=this.id.compareTo(stu.id);
if(num==0)
return this.name.compareTo(stu.name);
return num;
}
public String toString()
{
return id+"…"+name;
}

}
public class ManyMap {
public static void main(String args[])
{
HashMap<String,HashMap<String,String>>nyist=new HashMap<String,HashMap<String,String>>();//nyist学校名を定義
HashMap<String,String>jsjx=new HashMap<String,String>();//学部を定義
HashMap<String,String>ysx=new HashMap<String,String>();
nyist.put(“jsjx",jsjx);
nyist.put(“ysx",ysx);//学校に学部を追加
//学部にメンバーを追加
jsjx.put(“001″,"男");
jsjx.put(“002″,"女");
jsjx.put(“003″,"笹村");
ysx.put(“001″,"長尾");
ysx.put(“002″,"上村");
ysx.put(“003″,"山田");

HashMap<String,String>classes=nyist.get(“jsjx");
Set<Map.Entry<String,String>>entryset=classes.entrySet();

for(Iterator<Map.Entry<String,String>> it=entryset.iterator();it.hasNext();)
{
Map.Entry<String,String> me=it.next();
System.out.println(me.getKey()+"…"+me.getValue());
}

//nylistのすべてのメンバーを検索
Set<Map.Entry<String,HashMap<String,String>>>outentry=nyist.entrySet();
for(Iterator<Map.Entry<String,HashMap<String,String>>>it=outentry.iterator();it.hasNext();)
{
Map.Entry<String,HashMap<String,String>> out=it.next();//it.next()で学部を取得
System.out.println(“学部:"+out.getKey());
HashMap<String,String>inner=out.getValue();//hashmapの学部を取得
Set<Map.Entry<String,String>>clainner=inner.entrySet();
//System.out.println(clainner);
sop(clainner);
}
}
public static void sop(Set<?>list)
{
for(Iterator<?>it=list.iterator();it.hasNext();)
{
System.out.println(it.next());
}
}*/

HashMap<String,List<Student>>nyist = new HashMap<String,List<Student>>();
List<Student>jsjx=new ArrayList<Student>();
List<Student>ysx=new ArrayList<Student>();
nyist.put(“jsjx",jsjx);
nyist.put(“ysx",ysx);
jsjx.add(new Student(“001″,"島川"));
jsjx.add(new Student(“002″,"橋本"));
ysx.add(new Student(“0032″,"田中"));
ysx.add(new Student(“1230″,"重田"));
Set<Map.Entry<String,List<Student>>> entrykey = nyist.entrySet();
for(Iterator<Map.Entry<String,List<Student>>>it=entrykey.iterator();it.hasNext();)
{
Map.Entry<String,List<Student>> item=it.next();
System.out.println(“学部:"+item.getKey());
List<Student>stu=item.getValue();
/*for(Iterator<Student>iterator=stu.iterator();it.hasNext();)
{
System.out.println(it.next());
}*/
show(stu);
}
}
public static void show(List<?> list)
{
for(Iterator<?>it=list.iterator();it.hasNext();)
{
System.out.println(it.next());
}
}

}

Development

Posted by arkgame