關於java集合的練習

關於java集合的練習java

練習一:Collection集合練習

1、產生10個1-100的隨機數,並放到一個數組中,把數組中大於等於10的數字放到一個list集合中,並打印到控制檯。數組

 1 public class Topic1 {
 2     public static void main(String[] args) {
 3         ArrayList<Integer> list = new ArrayList<>();
 4         int arr[] = new int[10];
 5         Random ra = new Random();
 6         for (int i = 0; i < arr.length; i++) {
 7             arr[i]=ra.nextInt(100)+1;
 8             if (arr[i]>=10)
 9                 list.add(arr[i]);
10         }
11         System.out.println(list);
12     }
13 }

 

練習二:Collection集合練習

1、定義一個方法listTest(ArrayList<Integer> al, Integer s),要求返回s在al裏面第一次出現的索引,若是s沒出現過返回-1。dom

 1 public class Topic2 {
 2     public static void main(String[] args) {
 3         ArrayList<Integer> arrayList = new ArrayList<>();
 4         arrayList.add(1);
 5         arrayList.add(2);
 6         arrayList.add(6);
 7         arrayList.add(4);
 8         arrayList.add(9);
 9 
10         System.out.println("索引值爲:"+listTest(arrayList,4));
11     }
12    public static int  listTest(ArrayList<Integer> al, Integer s){
13 
14        for (int i = 0; i < al.size(); i++) {
15            if (al.get(i)==s)
16                return i;
17        }
18         return -1;
19    }
20 }

練習三:LinkedList使用

已知數組存放一批QQ號碼,QQ號碼最長爲11位,最短爲5位String[] strs = {"12345","67891","12347809933","98765432102","67891","12347809933"}。ide

將該數組裏面的全部qq號都存放在LinkedList中,將list中重複元素刪除,將list中全部元素分別用迭代器和加強for循環打印出來。函數

   

 1 import java.util.Iterator;
 2 import java.util.LinkedHashSet;
 3 import java.util.LinkedList;
 4 
 5 /*
 6 * 已知數組存放一批QQ號碼,QQ號碼最長爲11位,最短爲5位String[] strs = {"12345","67891","12347809933","98765432102","67891","12347809933"}。
 7 將該數組裏面的全部qq號都存放在LinkedList中,將list中重複元素刪除,將list中全部元素分別用迭代器和加強for循環打印出來。
 8 
 9 * */
10 public class Topic3 {
11     public static void main(String[] args) {
12         String[] strs = {"12345","67891","12347809933","98765432102","67891","12347809933"};
13         LinkedHashSet<String> set = method01(strs);
14         //方式1
15       //  System.out.println(set);
16         //方式2
17      //   System.out.println(method02(strs));
18         //迭代器打印
19         Iterator<String> it = method01(strs).iterator();
20         while (it.hasNext()){
21             String value = it.next();
22             System.out.print(value+" ");
23         }
24         System.out.println();
25         //加強for打印
26         for (String s : method02(strs)) {
27             System.out.print(s+" ");
28         }
29 
30     }
31     //方式2
32     private static LinkedList<String> method02(String[] strs) {
33         LinkedList<String> list = new LinkedList<>();
34         for (int i = 0; i < strs.length; i++) {
35             list.add(strs[i]);
36 
37 
38         }
39         int flag =1;// 0爲找不到,1爲找到
40         //若是此元素在,除了本次位置的其餘元素內找到,則刪除該元素.
41         for (int i = 0; i < list.size(); i++) {
42             //判斷這個元素以後的元素 是否與這個元素相等. 是則刪除,不是則繼續執行.
43             for(int j=i+1;j<list.size();j++){
44                 if (list.get(i).equals(list.get(j))){
45                     list.remove(j);
46                 }
47             }
48         }
49 
50         return list;
51     }
52     //方式1
53     private static LinkedHashSet<String> method01(String[] strs) {
54         LinkedHashSet<String> set = new LinkedHashSet<>();
55         for (int i = 0; i < strs.length; i++) {
56             set.add(strs[i]);
57         }
58         return set;
59     }
60 }

 

練習四:HashSet的使用

雙色球規則:雙色球每注投注號碼由6個紅色球號碼和1個藍色球號碼組成。紅色球號碼從1—33中選擇;藍色球號碼從1—16中選擇;請隨機生成一注雙色球號碼。(要求同色號碼不重複)this

 1 import java.util.ArrayList;
 2 import java.util.Random;
 3 /*
 4 * */
 5 public class Topic4 {
 6     public static void main(String[] args) {
 7         String stringArr[] = new String[7];
 8         //先肯定藍球位置 標記爲flag.
 9         int flag = 0;
10         Random ra = new Random();
11         int blueBallIndex = ra.nextInt(7);
12         stringArr[blueBallIndex]=method2();
13         for (int i = 0; i < stringArr.length; i++) {
14             if(i==blueBallIndex)
15                 continue;
16             stringArr[i]=method1();
17         }
18         //for循環打印
19         for (int i = 0; i < stringArr.length; i++) {
20             System.out.print(stringArr[i]+" ");
21         }
22     }
23 
24         //method1 返回紅球字符串
25         public static String method1(){
26             ArrayList<String> arrayList = new ArrayList<>();
27             for (int i = 0; i < 33; i++) {
28                 Integer temp = (i+1);
29                 arrayList.add(temp.toString());
30             }
31             Random ra = new Random();
32             int randomValue = ra.nextInt(33);
33             return "紅球"+arrayList.get(randomValue);
34         }
35         //method2 返回藍球字符串
36         public static String method2(){
37             ArrayList<String> arrayList = new ArrayList<>();
38             for (int i = 0; i < 16; i++) {
39                 Integer temp = (i+1);
40                 arrayList.add(temp.toString());
41             }
42             Random ra = new Random();
43             int randomValue = ra.nextInt(16);
44             return "藍球"+arrayList.get(randomValue);
45         }
46 
47 
48 }

練習五:Comparable和Comparator的使用

分別用Comparable和Comparator兩個接口對下列四位同窗的成績作降序排序,若是成績同樣,那在成績排序的基礎上按照年齡由小到大排序。編碼

姓名(String)spa

年齡(int)命令行

分數(float)code

liusan

20

90.0F

lisi

22

90.0F

wangwu

20

99.0F

sunliu

22

100.0F

編寫一個Student類用來實現Comparable<Student>接口,並在其中重寫CompareTo(Student o)方法  

 1 package topic5;
 2 
 3 public class Student implements  Comparable<Student> {
 4     private String name;
 5     private int age;
 6     private float sorce;
 7 
 8     public Student() {
 9     }
10 
11     public Student(String name, int age, float sorce) {
12         this.name = name;
13         this.age = age;
14         this.sorce = sorce;
15     }
16 
17     public String getName() {
18         return name;
19     }
20 
21     public void setName(String name) {
22         this.name = name;
23     }
24 
25     public int getAge() {
26         return age;
27     }
28 
29     public void setAge(int age) {
30         this.age = age;
31     }
32 
33     public float getSorce() {
34         return sorce;
35     }
36 
37     @Override
38     public String toString() {
39         return "Student{" +
40                 "name='" + name + '\'' +
41                 ", age=" + age +
42                 ", sorce=" + sorce +
43                 '}';
44     }
45 
46     public void setSorce(float sorce) {
47         this.sorce = sorce;
48     }
49 /*
50 *
51 * */
52     @Override
53     public int compareTo(Student o) {
54         //定義一箇中間變量判斷成績的大小 若是成績相等 比較年齡
55         int result = (int)(o.getSorce() - this.getSorce());
56         if(result==0){
57             result = o.getAge()-this.getAge();
58         }
59         return  result;
60       //  return (int)(o.getSorce() - this.getSorce());
61     }
62 }

在主函數中使用Comparable 與 Comparetor分別對ArrayList進行排序.

 1 import java.util.ArrayList;
 2 import java.util.Collections;
 3 import java.util.Comparator;
 4 
 5 /*
 6 * 分別用Comparable和Comparator兩個接口對下列四位同窗的成績作降序排序,若是成績同樣,那在成績排序的基礎上按照年齡由小到大排序。
 7 姓名(String)    年齡(int)    分數(float)
 8 liusan    20    90.0F
 9 lisi    22    90.0F
10 wangwu    20    99.0F
11 sunliu    22    100.0F
12 
13 * */
14 public class Topic5 {
15     public static void main(String[] args) {
16         Student stu1 = new Student("liusan",20,90.0f);
17         Student stu2 = new Student("lisi",22,90.0f);
18         Student stu3 = new Student("wangwu",20,90.0f);
19         Student stu4 = new Student("sunliu",20,100.0f);
20         System.out.println("升序排序");
21         ArrayList<Student > arr = new ArrayList<>();
22         arr.add(stu1);
23         arr.add(stu2);
24         arr.add(stu3);
25         arr.add(stu4);
26         Collections.sort(arr);
27         System.out.println(arr);
28         //打亂從新寫方法排序
29         Collections.shuffle(arr);
30         //寫一個Compelator方法
31         Collections.sort(arr, new Comparator<Student>() {
32             @Override
33             public int compare(Student o1, Student o2) {
34                 int result = (int)(o2.getSorce() - o1.getSorce());
35                 if(result==0){
36                     result = o2.getAge()-o1.getAge();
37                 }
38                 return  result;
39 
40             }
41         });
42         System.out.println("升序排序");
43         System.out.println(arr);
44 
45     }
46 }

練習六:Map集合的使用(一)

1、如今有一個map集合以下:

Map<Integer,String> map = new HashMap<Integer, String>();
        map.put(1, "張三丰");
        map.put(2, "周芷若");
        map.put(3, "汪峯");
        map.put(4, "滅絕師太");

要求:

1.遍歷集合,並將序號與對應人名打印。

2.向該map集合中插入一個編碼爲5姓名爲李曉紅的信息

       3.移除該map中的編號爲1的信息

       4.將map集合中編號爲2的姓名信息修改成"周林"

 1 import java.util.HashMap;
 2 import java.util.Map;
 3 import java.util.Set;
 4 
 5 /*
 6 * 1、如今有一個map集合以下:
 7 Map<Integer,String> map = new HashMap<Integer, String>();
 8         map.put(1, "張三丰");
 9         map.put(2, "周芷若");
10         map.put(3, "汪峯");
11         map.put(4, "滅絕師太");
12 
13 *要求:
14 1.遍歷集合,並將序號與對應人名打印。
15 2.向該map集合中插入一個編碼爲5姓名爲李曉紅的信息
16     3.移除該map中的編號爲1的信息
17     4.將map集合中編號爲2的姓名信息修改成"周林"
18 
19 *
20 * */
21 public class Topic6 {
22     public static void main(String[] args) {
23         Map<Integer,String> map = new HashMap<Integer, String>();
24         map.put(1, "張三丰");
25         map.put(2, "周芷若");
26         map.put(3, "汪峯");
27         map.put(4, "滅絕師太");
28         //1.遍歷集合,並將序號與對應人名打印。
29        for(Map.Entry<Integer,String> entry:map.entrySet()){
30            System.out.println(entry.getKey()+ " "+ entry.getValue());
31        }
32         System.out.println("================");
33         //3.移除該map中的編號爲1的信息
34         map.remove(1);
35         for(Map.Entry<Integer,String> entry:map.entrySet()){
36             System.out.println(entry.getKey()+ " "+ entry.getValue());
37         }
38         System.out.println("================");
39         //4.將map集合中編號爲2的姓名信息修改成"周林"
40         map.put(2,"周林");
41         for(Map.Entry<Integer,String> entry:map.entrySet()){
42             System.out.println(entry.getKey()+ " "+ entry.getValue());
43         }
44     }
45 }

練習七:Map集合的使用(二)

1、有2個數組,第一個數組內容爲:[黑龍江省,浙江省,江西省,廣東省,福建省],第二個數組爲:[哈爾濱,杭州,南昌,廣州,福州],將第一個數組元素做爲key,第二個數組元素做爲value存儲到Map集合中。如{黑龍江省=哈爾濱, 浙江省=杭州, …}。

 1 import java.util.HashMap;
 2 import java.util.Map;
 3 
 4 /*
 5 * 2、有2個數組,第一個數組內容爲:[黑龍江省,浙江省,江西省,廣東省,福建省],第二個數組爲:[哈爾濱,杭州,南昌,廣州,福州],將第一個數組元素做爲key,
 6 * 第二個數組元素做爲value存儲到Map集合中。如{黑龍江省=哈爾濱, 浙江省=杭州, …}。
 7 * */
 8 public class Topic7 {
 9     public static void main(String[] args) {
10         String str1[] = {"黑龍江省","浙江省","江西省","廣東省","福建省"};
11         String str2[] = {"哈爾濱","杭州","南昌","廣州","福州"};
12         HashMap<String,String> map = new HashMap<>();
13         for (int i = 0; i < str1.length; i++) {
14             for (int j = 0; j < str2.length; j++) {
15                 map.put(str1[i],str2[j]);
16             }
17         }
18         System.out.print("{");
19         for (Map.Entry<String,String> entry: map.entrySet()){
20             System.out.printf("%s=%s,",entry.getKey(),entry.getValue());
21         }
22         System.out.println("}");
23     }
24 }

練習八:Map集合的使用(三)

1、定義一個泛型爲String類型的List集合,統計該集合中每一個字符(注意,不是字符串)出現的次數。例如:集合中有」abc」、」bcd」兩個元素,程序最終輸出結果爲:「a = 1,b = 2,c = 2,d = 1」。

 1 import java.util.*;
 2 
 3 /*
 4 * 3、定義一個泛型爲String類型的List集合,統計該集合中每一個字符(注意,不是字符串)出現的次數。
 5 * 例如:集合中有」abc」、」bcd」兩個元素,
 6 * 程序最終輸出結果爲:「a = 1,b = 2,c = 2,d = 1」。
 7 * */
 8 public class Topic8 {
 9     public static void main(String[] args) {
10         //定義一個String類型的List集合,用來存儲題目給定的字符串
11         LinkedList<String> list = new LinkedList<>();
12         list.add("abc");
13         list.add("bcd");
14         //將集合中的兩個元素進行拼接,調用method1(String str) 進行統計,篩選.
15         String str = list.get(0)+list.get(1);
16         method1(str);
17     }
18     private static void method1(String str) {
19 
20         //1. 建立Map集合,key是字符串中的字符,value是字符的個數
21         //因爲HashMap具備篩選功能,能夠幫助咱們對字符進行統計.
22         HashMap<Character,Integer> map = new HashMap<>();
23         //2.將形式參數傳遞過來的字符串使用toCharArray()的方法轉換成Char類型的字符數組.c用來遍歷獲取字符數組中的每個值.
24         for(char c :str.toCharArray()){
25             //對於字符串"abcbcd"爲例,char c =a; map.containKey(a)爲false,執行:號後的1
26             //map.put(a,1); 這樣就將a字符與對應的數量添加到了map集合中.
27             map.put(c,map.containsKey(c)?map.get(c)+1:1);
28         }
29         //獲取最後一個key
30         Set<Character> chrs = map.keySet();
31         List list = new ArrayList(chrs);
32         char lastKey = (char)(list.get(list.size()-1));
33         //char lastKey =  (char)list.lastIndexOf("d");
34      //   System.out.println(lastKey);
35         for(Map.Entry<Character,Integer> entry : map.entrySet()){
36             char key = entry.getKey();
37             int value = entry.getValue();
38             //若是是最後一個key直接打印key與value結束.
39             if (key == lastKey)
40             {
41                 System.out.println(key+"="+value);
42                 break;
43             }
44             //若是不是最後一個,打印 key與value和一個逗號分隔
45             System.out.print(key+"="+value+",");
46 
47         }
48 
49     }
50 }

練習九:Map集合的使用(四)

1、利用Map,完成下面的功能:

從命令行讀入一個字符串,表示一個年份,輸出該年的世界盃冠軍是哪支球隊。若是該 年沒有舉辦世界盃,則輸出:沒有舉辦世界盃。

//tips:參閱Map接口containsKey(Object key)方法 

 

2、在原有世界盃Map 的基礎上,增長以下功能: 讀入一支球隊的名字,輸出該球隊奪冠的年份列表。 例如,讀入「巴西」,應當輸出 1958 1962 1970 1994 2002 讀入「荷蘭」,應當輸出 沒有得到過世界盃 

//tips:參閱Map接口containsValue(Object value)方法

示例:

 

 

附:歷屆世界盃冠軍

屆數

舉辦年份

舉辦地點

冠軍

第一屆

1930年

烏拉圭

烏拉圭

第二屆

1934年

意大利

意大利

第三屆

1938年

法國

意大利

第四屆

1950年

巴西

烏拉圭

第五屆

1954年

瑞士

西德

第六屆

1958年

瑞典

巴西

第七屆

1962年

智利

巴西

第八屆

1966年

英格蘭

英格蘭

第九屆

1970年

墨西哥

巴西

第十屆

1974年

前西德

西德

第十一屆

1978年

阿根廷

阿根廷

第十二屆

1982年

西班牙

意大利

第十三屆

1986年

墨西哥

阿根廷

第十四屆

1990年

意大利

西德

第十五屆

1994年

美國

巴西

第十六屆

1998年

法國

法國

第十七屆

2002年

韓日

巴西

第十八屆

2006年

德國

意大利

第十九屆

2010年

南非

西班牙

第二十屆

2014年

巴西

德國

 1 import java.util.HashMap;
 2 import java.util.Map;
 3 import java.util.Scanner;
 4 
 5 public class Topic9 {
 6     public static void main(String[] args) {
 7         HashMap<Integer,String> map = new HashMap<>();
 8         map.put(1930,"烏拉圭");
 9         map.put(1934,"意大利");
10         map.put(1938,"意大利");
11         map.put(1950,"烏拉圭");
12         map.put(1954,"西德");
13         map.put(1958,"巴西");
14         map.put(1962,"巴西");
15         map.put(1966,"英格蘭");
16         map.put(1970,"巴西");
17         map.put(1974,"西德");
18         map.put(1978,"阿根廷");
19         map.put(1982,"意大利");
20         map.put(1986,"阿根廷");
21         map.put(1990,"西德");
22         map.put(1994,"巴西");
23         map.put(1998,"法國");
24         map.put(2002,"巴西");
25         map.put(2006,"意大利");
26         map.put(2010,"西班牙");
27         map.put(2014,"德國");
28         System.out.println("請輸入年份:");
29         Scanner sc = new Scanner(System.in);
30         int inputNum = sc.nextInt();
31         for (Map.Entry<Integer,String> entry: map.entrySet()){
32             int key = entry.getKey();
33             String value = entry.getValue();
34             if (inputNum==key)
35                 System.out.println(key+"年得到世界盃冠軍的是:"+value);
36         }
37         String temp = sc.nextLine();
38         System.out.println("請輸入國家名稱");
39         String inputStr = sc.nextLine();
40         int flag = 0;//標記沒有奪冠
41         for (Map.Entry<Integer,String> entry: map.entrySet()){
42             if(entry.getValue().equals(inputStr)){
43                 System.out.println(entry.getKey()+".");
44                 flag=1;
45             }
46         }
47         if(flag==0){
48             System.out.println("沒有得到過世界盃");
49         }
50 
51     }
52 }

練習十:綜合練習

1.站編號和站名對應關係以下:

            1=朱辛莊

            2=育知路

            3=平西府

            4=回龍觀東大街

            5=霍營

       //....

將以上對應關係的數據存儲到map集合中,key:表示站編號,value:表示站名,並遍歷打印(能夠不按順序打印):

       第10站: 森林公園南門

       第6站: 育新

       第12站: 奧體中心

       第13站: 北土城

       //...

2.計算地鐵票價規則:

       總行程 3站內(包含3站)收費3元,

            3站以上但不超過5站(包含5站)的收費4元,

            5站以上的,在4元的基礎上,每多1站增長2元,

            10元封頂;

3.打印格式(須要對鍵盤錄入的上車站和到達站進行判斷,若是沒有該站,提示從新輸入,直到站名存在爲止):

       注意:每站須要2分鐘

       請輸入上車站:

       沙河

       您輸入的上車站:沙河不存在,請從新輸入上車站:

       上地

       您輸入的上車站:上地不存在,請從新輸入上車站:

       朱辛莊

       請輸入到達站:

       沙河

       您輸入的到達站:沙河不存在,請從新輸入到達站:

       西二旗

       您輸入的到達站:西二旗不存在,請從新輸入到達站:

       西小口

       從朱辛莊到西小口共通過6站收費6元,大約須要 12分鐘

 

  1 import java.util.LinkedHashMap;
  2 import java.util.Map;
  3 import java.util.Scanner;
  4 
  5 public class Topic10 {
  6     public static void main(String[] args) {
  7         /*建立一個LinkedHashMap用來存儲地鐵站編號 以及 地鐵站名稱*/
  8         LinkedHashMap<Integer, String> map = new LinkedHashMap<>();
  9         map.put(1, "朱辛莊");
 10         map.put(2, "育知路");
 11         map.put(3, "平西府");
 12         map.put(4, "回龍觀東大街");
 13         map.put(5, "霍營");
 14         map.put(6, "育新");
 15         map.put(7, "西小口");
 16         map.put(8, "永泰莊");
 17         map.put(9, "林萃橋");
 18         map.put(10, "森林公園南門");
 19         map.put(11, "奧林匹克公園");
 20         map.put(12, "奧體中心");
 21         map.put(13, "北土城");
 22       
 23         //聲明上車時的地鐵站 和 下車時的地鐵站
 24         String upStation;
 25         String downStation;
 26 
 27         Scanner sc = new Scanner(System.in);
 28         //聲明上車時的key,下車時的key
 29         int beforeKey = 0, afterKey = 0;
 30         //無限循環判斷用戶輸入
 31         // 1.若是輸入不合法繼續請求用戶輸入
 32         // 2.若是輸入合法就記錄 上車的地鐵站名稱 以及 上錯車的地鐵站編號
 33         // break跳出無限循環.
 34         for (; ; ) {
 35             System.out.println("請輸入上車的車站:");
 36             upStation = sc.nextLine();
 37             if (map.containsValue(upStation)) {
 38                 System.out.println("請上車!");
 39                 for (Map.Entry<Integer, String> entry : map.entrySet()) {
 40                     if (entry.getValue().equals(upStation)) {
 41                         //記錄本次車站的key值
 42                         beforeKey = entry.getKey();
 43 
 44                     }
 45                 }
 46                // System.out.println(beforeKey);
 47                 break;
 48             }
 49             else {
 50                 System.out.println(upStation + "不存在,請從新輸入上車站:");
 51             }
 52 
 53         }
 54         //==============================================
 55         //當上車的地鐵站輸入正確,並正確記錄後
 56         //請求用戶輸入
 57         for (; ; ) {
 58             System.out.println("請輸入下車的車站:");
 59             downStation = sc.nextLine();
 60             if (map.containsValue(downStation)) {
 61                 System.out.println("請上車!");
 62                 for (Map.Entry<Integer, String> entry : map.entrySet()) {
 63                     if (entry.getValue().equals(downStation)) {
 64                         //記錄本次車站的key值
 65                         afterKey = entry.getKey();
 66 
 67                     }
 68                 }
 69                 // System.out.println(beforeKey);
 70                 break;
 71             }
 72             else {
 73                 System.out.println(downStation + "不存在,請從新輸入下車站:");
 74             }
 75 
 76         }
 77         /*
 78          * 總行程 3站內(包含3站)收費3元,
 79           3站以上但不超過5站(包含5站)的收費4元,
 80           5站以上的,在4元的基礎上,每多1站增長2元,
 81           10元封頂;
 82 
 83         * */
 84         int value = afterKey - beforeKey;
 85         int prize=0;
 86         int time=0;
 87         if (value<=3)
 88         {
 89             prize=3;
 90 
 91         }
 92         else if(value>3 &&value<=5)
 93         {
 94             prize=4;
 95 
 96         }
 97         else if (value>5 && value<=9)
 98         {
 99             prize=(value-5)*2+4;
100             //若是prize計算的價格超過了10R,則將10賦值給prize
101             if (prize>=10)
102                 prize=10;
103         }
104         else
105             prize=10;
106         System.out.printf("從%s到%s通過%d站收費%d元,大約須要%d分鐘\n",upStation,downStation,value,prize,value*2);
107 
108     }
109 }
相關文章
相關標籤/搜索