The method of nesting Java collections
This article mainly explains "the method of nesting Java collections". Interested friends may wish to have a look at it. The method introduced in this paper is simple, fast and practical. Next let the editor to take you to learn the "Java collection nesting method" bar!
First, requirements: create an ArrayList collection, store three elements, each element is HashMap, each HashMap key and value is String, and traverse
Analysis:
1. Create an ArrayList collection
two。 Create a HashMap collection whose keys and values are String
3. Add HashMap as an element to ArrayList
4. Ergodic
Public static void main (String [] args) {/ / create ArrayList collection ArrayList al=new ArrayList (); / / create HashMap collection HashMaphm=new HashMap (); / / add key value pairs hm.put ("01", "Zhang San"); hm.put ("03", "Wang Wu"); hm.put ("02", "Li Si") / / create HashMap collection HashMaphm1=new HashMap (); / / add key value pairs hm1.put ("05", "Zhang"); hm1.put ("04", "Wang"); hm1.put ("07", "Li"); / / put HashMap into ArrList al.add (hm); al.add (hm1) / / traversing for (HashMap ss: al) {/ / the inner layer is still the traversal method of HashMap Set key = ss.keySet (); for (String key1: key) {String value = ss.get (key1); System.out.println (key1 + "," + value);}
Requirements: create a HashMap collection that stores three key-value pairs of elements, each of which has a key of String and a value of ArrayList
Analysis:
1. Create a HashMap collection with the key String and the value ArrayList
two。
3. Add ArrayList as a value to the HashMap collection
4. Traversing the HashMap collection
Public class HashMapInculdingArrayLis {public static void main (String [] args) {/ / create HashMap collection HashMap hm=new HashMap (); / / create ArrayList collection object ArrayList al=new ArrayList (); al.add ("Zhang San"); ArrayList al1=new ArrayList (); ArrayList al2=new ArrayList (); al2.add ("Wang Wu"); al1.add ("Li Si") Hm.put ("01", al); hm.put ("02", al1); hm.put ("03", al2); / / traversal SetkeySet = hm.keySet (); for (String key:keySet) {System.out.print (key+ ","); ArrayList strings = hm.get (key) For (String value:strings) {System.out.println (value);} at this point, I believe you have a deeper understanding of the "nesting method of Java collections". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!