設個User類:數組
public class User { private String userName; private String userId; private String userInfo; public User(){} public User(String userName, String userId, String userInfo) { this.userName = userName; this.userId = userId; this.userInfo = userInfo; } //getter setter
}
1)foreach方法app
//foreach
public Map<String,User> ltmForEach(List<User> list){ Map<String,User> map = new HashMap<>(); list.forEach(user -> { map.put(user.getUserId(), user); }); return map; }
2)stream()方法工具
//stream()
public Map<String,User> ltmStream(List<User> list){ /** * Collectors.toMap()方法參數: * keyMapper: User::getUserId,調用User的getter方法 * valueMapper: user->user, User類做爲value * mergeFunction: 當key衝突時,value合併的方法:(n1,n2)->n2爲替換,(n1,n2)->n1+n2爲累加 * mapSupplier: Map構造器,須要返回特定Map的時候使用,如TreeMap::new返回以key排序的Map */
return list.stream() .collect(Collectors.toMap(User::getUserId,user->user,(n1,n2)->n2,TreeMap::new)); }
3)Map經常使用遍歷方法this
// 1. 加強for循環
Map<String, User> ltmStreamMap = l.ltmStream(list); for(Map.Entry entry : ltmStreamMap.entrySet()){ System.out.println(entry.getKey()+" : "+entry.getValue()); } // 2. Iterator迭代器
Map<String, User> ltmForEachMap = l.ltmForEach(list); Iterator<Map.Entry<String, User>> iterator = ltmForEachMap.entrySet().iterator(); while(iterator.hasNext()){ Map.Entry<String, User> next = iterator.next(); System.out.println(next.getKey()+" : "+next.getValue()); } // 3. 內循環
Map<String, User> ltmForEachMap = l.ltmForEach(list); ltmForEachMap.forEach((k,v)->{ System.out.println(k+" : "+v); });
Array指數組類型數據,如:String[]、Object[]、int[]等spa
通常使用工具類Arrays的asList方法:code
public class arrayToList { public static void main(String[] args) { String[] strs = new String[]{"a","b","c"}; List<String> list = Arrays.asList(strs); for(String str : list){ System.out.println(str); } } }
集合List轉爲數組類型Arrayblog
一般使用Collection的toArray方法排序
public class listToArray { public static void main(String[] args) { List<String> list = new ArrayList<>(); list.add("a"); list.add("b"); list.add("c"); //List->Array,申請大小爲list.size()的數組空間
String[] strs = list.toArray(new String[list.size()]); } }
public class arrayToSet { public static void main(String[] args) { /** * Array數組類型轉爲Set類型集合 * 須要Array->List->Set */ String[] strs = new String[]{"a","b","c"}; Set<String> set = new HashSet<>(Arrays.asList(strs)); /** * Set轉爲Array和List轉爲Array原理相同 */ strs = set.toArray(new String[set.size()]); } }
List和Set都實現了Collection藉口,Collection.addAll()方法get
相互轉換能夠經過:it
1)Collection.addAll()
2)構造方法直接傳入List/Set
/**
* List -> Set */ Set set = new HashSet(list);//構造傳參
set.addAll(list);//Collection.addAll()
/** * Set -> List */ List list = new ArrayList(set); list.addAll(set);