集合的练习

  1. 案例一:自动选择器:

     

     

     

     

  2. 案例一代码实现:
    import java.util.*;

    public class text {
    public static void main(String[] args) {
    //第一种实现方式
    List<String> list=new ArrayList<>();
    Collections.addAll(list,"张三","李四","王五","赵六","前妻");
    Random random=new Random();
    int i = random.nextInt(list.size());
    String s=list.get(i);
    System.out.println(s);
    //第二种实现方式
    Collections.shuffle(list);
    System.out.println(list.get(0));

    }
    }
  3. 案例2:

     

     

  4. 案例二代码实现:
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.Random;

    public class text2 {
    public static void main(String[] args) {
    //创建集合
    ArrayList<Integer> arrayList=new ArrayList<>();
    //添加数据
    Collections.addAll(arrayList,1,1,1,1,1,1,1);
    Collections.addAll(arrayList,0,0,0);
    //打乱集合中的数据
    Collections.shuffle(arrayList);
    //从集合中随机抽取0或1
    Random random=new Random();
    int index = random.nextInt(arrayList.size());
    int number=arrayList.get(index);
    //创建两个集合分别储存男生和女生的名字
    ArrayList<String> boyList=new ArrayList<>();
    ArrayList<String> girlList=new ArrayList<>();
    //添加数据
    Collections.addAll(boyList,"刘宇坚","李进","许德俊","周文杰","张宇坤");
    Collections.addAll(boyList,"邱静","张芊","熊伟仪");
    //根据0和1从集合中取值
    if (number==1){
    int bindex=random.nextInt(boyList.size());
    System.out.println(boyList.get(bindex));
    }else {
    int gindex=random.nextInt(boyList.size());
    System.out.println(boyList.get(gindex));
    }
    }
    }
  5. 案例3:

     

     

  6. 案例3代码实现;

     

     

  7. 案例4:

     

     

  8. 案例5:
    import java.util.*;

    public class text4 {
    public static void main(String[] args) {
    HashMap<String, ArrayList<String>> hashMap=new HashMap<>();
    ArrayList<String> list=new ArrayList<>();
    Collections.addAll(list,"万年","上饶");
    hashMap.put("江西",list);
    Set<Map.Entry<String, ArrayList<String>>> entries = hashMap.entrySet();
    for (Map.Entry<String, ArrayList<String>> entry : entries) {
    String key = entry.getKey();
    ArrayList<String> value = entry.getValue();
    StringBuilder stringBuilder=new StringBuilder();
    for (String s : value) {
    System.out.println(s);
    stringBuilder.append(s);
    }
    System.out.println(key+stringBuilder.toString());


    }

    }
    }
posted @ 2023-04-13 21:40  为zq  阅读(19)  评论(0)    收藏  举报