转载

Java (List & Map) –创建, 写入, 迭代 & 排序_Java指南

Java java.util.List & java.util.Map 是一种使用频率非常高的数据结构, 我们将尝试如何创建,写入,迭代和对object类型数据进行排序

 目标:

  • 如何创建,初始化List & Map?
  • 如何写入List & Map?
  • 如何迭代每个元素 List 或者 Map?
  • 如何通过key或者values对List & MaP排序?
  • 如何将Map转成List?
在下面的例子里,我们将使用一个简单的"POJO"
package com.collections.two; public class Person implements Comparable<Person>{ private int age; private String name; public Person(String name, int age){ this.name = name; this.age = age; } @Override public int compareTo(Person person) { return this.age-person.getAge(); } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } }  

( 1 ) java.util.List “LinkedList & ArrayList”

java.util.List是一个接口,他有很多实现,像 LinkedList & ArrayList就是其中之一。
  • 创建List
List<Person> arrayList = new ArrayList<Person>();
List<Person> linkedList = new LinkedList<Person>();
  • 写入List
arrayList.add(new Person());
linkedList.add(new Person());
  • 迭代List
我们又2种方式可以选择,第2种更加高效
for(int i = 0; i < linkedList.size(); i++){
      System.out.println("LinkedList[ "+i+"]"+linkedList.get(i));          
}
//this is an efficient way to iterate
for(Person person:linkedList){
    System.out.println("LinkedList: "+person);
}
  • 排序LIst
为了使用 Collections.sort(),list里面存储的对象Person必须实现Comparable接口
Collections.sort(linkedList);
  示例代码:
package com.collections.two; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedList; import java.util.List; public class ListApp { public static void main( String[] args ) { // ( 1 ) List // A. Initiate List<Person> arrayList = new ArrayList<Person>(); List<Person> linkedList = new LinkedList<Person>(); // B. Populate for(Person person:getPersons()){ arrayList.add(person); linkedList.add(person); } // --> print System.out.println("--------- Print All -------------"); System.out.println("ArrayList: "+arrayList); System.out.println("LinkedList: "+linkedList); // C. Iterate System.out.println("--------- Print Iterate by index -------------"); for(int i = 0; i < linkedList.size(); i++){ System.out.println("LinkedList[ "+i+" ]"+linkedList.get(i)); } System.out.println("--------- Print Iterate by for each -------------"); //this is an efficient way to iterate for(Person person:linkedList){ System.out.println("LinkedList: "+person); } // D. Sort Collections.sort(linkedList); // --> print System.out.println("--------- Print Sorted List -------------"); System.out.println("Sorted LinkedList: "+linkedList); } private static Person[] getPersons(){ Person[] persons = new Person[5]; persons[0] = new Person("Brit", 29); persons[1] = new Person("John", 32); persons[2] = new Person("Jack", 27); persons[3] = new Person("Jenifer", 24); persons[4] = new Person("Brit", 37); return persons; } }  
 

( 2 ) java.util.Map “HashMap & TreeMap”

   
  • 创建Map
Map<String,Person> hashMap = new HashMap<String,Person>();
Map<String,Person> treeMap = new TreeMap<String,Person>();
  • 填充Map
如果我们插入很多实体,TreeMap会保持顺利
hashMap.put("key",new Person());
treeMap.put("key",new Person());
  • 迭代map
有2种方式 第1种方式,通过 get keys()我们调用map.get(key)能得到值
for(String key:treeMap.keySet()){
System.out.println("treeMap: [key: "+key+" , value: "+treeMap.get(key));
}
第2种方式是通过 Map.Entry,一个个遍历里面的记录
for(Entry<String, Person> entry:treeMap.entrySet()){
System.out.println("treeMap: [key: "+entry.getKey()+" , value: "+entry.getValue());
        }
  • 排序map
为了保证顺利,排序结果需要存储在TreeMap
TreeMap<String,Person> sorted_map = new TreeMap<String,Person>(new ValueComparator());
sorted_map.putAll(hashMap);
我们需要定义一个comparator去比较key对象
class ValueComparator implements Comparator {
      Map map;
      public ValueComparator(){
      }
      public int compare(Object keyA, Object keyB){
        return ((String) keyA).compareTo((String) keyB);
      }
}
  • Map转换成List
如果你想提取map的值到list里面,你可以这样做 List<Person> persons = new ArrayList<Person>(sorted_map.values());

完整的例子

package com.collections.two; import java.util.ArrayList; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.TreeMap; public class MapApp { public static void main( String[] args ) { // ( 1 ) Map // A. Initiate Map<String,Person> hashMap = new HashMap<String,Person>(); Map<String,Person> treeMap = new TreeMap<String,Person>(); // B. Populate int k = 0 ; for(Person person:getPersons()){ hashMap.put(""+k,person); treeMap.put(""+k++,person); } // --> print System.out.println("--------- Print All -------------"); System.out.println("HashMap: "+hashMap); System.out.println("TreeMap: "+treeMap); // C. Iterate // --> print System.out.println("--------- Print Iterate by get(key) -------------"); for(String key:treeMap.keySet()){ System.out.println("treeMap: [key: "+key+" , value: "+treeMap.get(key)); } // --> print System.out.println("--------- Print Iterate by Entry -------------"); for(Entry<String, Person> entry:treeMap.entrySet()){ System.out.println("treeMap: [key: "+entry.getKey()+" , value: "+entry.getValue()); } // D. Sort by value TreeMap<String,Person> sorted_map = new TreeMap<String,Person>(new ValueComparator()); sorted_map.putAll(hashMap); // --> print System.out.println("--------- Print Sorted Map by Value -------------"); System.out.println("Sorted HashMap: "+sorted_map); // E. Convert Map to List List<Person> persons = new ArrayList<Person>(sorted_map.values()); // --> print System.out.println("--------- Print List<Person> -------------"); System.out.println("List<Person>: "+persons); } private static Person[] getPersons(){ Person[] persons = new Person[5]; persons[0] = new Person("Brit", 29); persons[1] = new Person("John", 32); persons[2] = new Person("Jack", 27); persons[3] = new Person("Jenifer", 24); persons[4] = new Person("Brit", 37); return persons; } } class ValueComparator implements Comparator { Map map; public ValueComparator(){ } public int compare(Object keyA, Object keyB){ return ((String) keyA).compareTo((String) keyB); } }
正文到此结束
Loading...