java 数组和容器的简单使用:
// 数组的使用
int [] array = {1,2,3,4};
System.out.println( array );
System.out.format( "index 2:%d\n",array[2] );
// list 使用
List<Integer> list = new ArrayList<Integer>();
list.add( 10 );
list.add( 11 );
list.add( 12 );
// 遍历
for(Integer data: list) {
System.out.println( "list:" + data );
}
// hash map 使用
Map< String, Integer > m = new HashMap< String, Integer >();
m.put( "zhangsan", 19 );
m.put( "lisi", 49 );
m.put( "wangwu", 19 );
m.put( "lisi", 20 );
m.put( "hanmeimei", 0 );
// 遍历
Iterator it = m.keySet().iterator();
while( it.hasNext() )
{
String key;
int value;
key = it.next().toString();
value = m.get(key);
System.out.println( key+"--" + value );
}
// set 使用
Set<Integer> inset = new HashSet<Integer>();
inset.add(2);
inset.add(2);
inset.add(3);
Iterator iterator = inset.iterator();
while (iterator.hasNext())
{
System.out.println( "inset:"+iterator.next() );
}
根据字段进行排序:
// 根据字段排序
static void test7()
{
class CPerson {
int index;
String name;
int age;
}
List<CPerson> people = new ArrayList<CPerson>();
CPerson p1 = new CPerson();
p1.age = 6;
p1.name = "nick";
p1.index = 0;
CPerson p2 = new CPerson();
p2.index = 1;
p2.age = 12;
p2.name = "jhon";
CPerson p3 = new CPerson();
p3.index = 2;
p3.age = 3;
p3.name = "amy";
people.add(p1);
people.add(p2);
people.add(p3);
// 用 lambda 排序
people.sort((h1, h2) -> h1.age - h2.age);
//people.sort((h1, h2) -> h2.age - h1.age);
/*
// 从小到大
Collections.sort(people, new Comparator<CPerson>() {
public int compare(CPerson u1, CPerson u2) {
if (u1.age > u2.age) {
return 1;
}
if (u1.age == u2.age) {
return 0;
}
return -1;
}
});
// 从大到小的顺序
Collections.sort(people, new Comparator<CPerson>() {
public int compare(CPerson u1, CPerson u2) {
if (u1.age > u2.age) {
return -1;
}
if (u1.age == u2.age) {
return 0;
}
return 1;
}
});
*/
for (CPerson u : people) {
System.out.format( "index:%d age:%d name%s", u.index, u.age, u.name );
}
}