16 集合(下)

简介: 16 集合(下)

5.第五题(Map)设计Account 对象如下:

private long id;  
 private double balance;  
 private String password;

要求完善设计,使得该Account 对象能够自动分配id。 给定一个List 如下:

List list = new ArrayList(); 
list.add(new Account(10.00, “1234”)); 
list.add(new Account(15.00, “5678”)); 
list.add(new Account(0, “1010”));


要求把List 中的内容放到一个Map 中,该Map 的键为id,值为相应的Account 对象。 最后遍历这个Map,打印所有Account 对象的id 和余额。


image.png

image.png

package com.company;
import java.util.UUID;
/**
 * Created by ttc on 2018/1/11.
 */
public class Account {
    private String sid;//使用UUID来生成
    private double balance;
    private String password;
    public Account(double balance, String password)
    {
        this.balance = balance;
        this.password = password;
        //自动分配账号
        this.sid = UUID.randomUUID().toString();
    }
    public String getSid() {
        return sid;
    }
    public void setSid(String sid) {
        this.sid = sid;
    }
    public double getBalance() {
        return balance;
    }
    public void setBalance(double balance) {
        this.balance = balance;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
}

package com.company;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * Created by ttc on 2018/1/11.
 */
public class TestAccount {
    public static void main(String[] args) {
        List<Account> accountList = new ArrayList<>();
        accountList.add(new Account(100,"123"));
        accountList.add(new Account(10,"456"));
        accountList.add(new Account(80,"111"));
        //将数据转移到map结构
        Map<String,Account> accountMap = new HashMap<String,Account>();
        for(Account account : accountList)
        {
            accountMap.put(account.getSid(),account);
        }
        for(Map.Entry<String,Account> entry: accountMap.entrySet())
        {
            System.out.println(entry.getKey() + "   " + entry.getValue().getSid());
        }
    }
}

Account的id自增长版本

package com.company;
import java.util.UUID;
/**
 * Created by ttc on 2018/1/11.
 */
public class Account {
//    private String sid;//使用UUID来生成
    private long sid;
    private double balance;
    private String password;
    private static int object_count = 0;
    public Account(double balance, String password)
    {
        this.balance = balance;
        this.password = password;
        //自动分配账号
        //this.sid = UUID.randomUUID().toString();
        //先获得当前本类已经创建了多少个对象
        this.sid = Account.object_count + 1;
        Account.object_count++;
    }
    public long getSid() {
        return sid;
    }
    public void setSid(long sid) {
        this.sid = sid;
    }
    public double getBalance() {
        return balance;
    }
    public void setBalance(double balance) {
        this.balance = balance;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
}

public static void main(String[] args) {
        List<Account> accountList = new ArrayList<>();
        accountList.add(new Account(100,"123"));//A
        accountList.add(new Account(10,"456"));//B
        accountList.add(new Account(80,"111"));
        accountList.add(new Account(330,"333"));
        //将数据转移到map结构
        Map<Long,Account> accountMap = new HashMap<Long,Account>();
        for(Account account : accountList)
        {
            accountMap.put(account.getSid(),account);
        }
        for(Map.Entry<Long,Account> entry: accountMap.entrySet())
        {
            System.out.println(entry.getKey() + "   " + entry.getValue().getSid());
        }
    }

6.第六题(List)已知有一个Worker 类如下:

public class Worker
 { private int age; 
private String name; 
private double salary; 
public Worker (){} 
public Worker (String name, int age, double salary)
{ this.name = name; 
this.age = age; 
this.salary = salary; } 
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; } 
public double getSalary(){ return salary; } 
public void setSalary(double salary){ this.salary = salary; } 
public void work(){ 
System.out.println(name + “ work”); } }

完成下面的要求

  1. 创建一个List,在List 中增加三个工人,基本信息如下:

姓名 年龄 工资

zhang3 18 3000

li4 25 3500

wang5 22 3200

  1. 在li4 之前插入一个工人,信息为:姓名:zhao6,年龄:24,工资3300
  2. 删除wang5 的信息
  3. 利用for 循环遍历,打印List 中所有工人的信息
  4. 利用迭代遍历,对List 中所有的工人调用work 方法。


image.png

image.png

List<Worker> workerList = new ArrayList<>();
        workerList.add(new Worker("zhangsan",12,2445));
        workerList.add(new Worker("lisi",32,5445));
        workerList.add(new Worker("wangwu",22,7445));
        Worker worker = new Worker("zhaoliu",33,5645);
        workerList.add(1,worker);
        workerList.remove(3);
        for(int i = 0; i < workerList.size();i++)
        {
            System.out.println(workerList.get(i));
        }
        for(Worker worker1 : workerList){
            worker1.work();
        }

经典练习


一篇英文文章,单词间用空格分割,统计出现了哪些单词,以及每个单词出现的次数。

public static void main(String[] args) {
        //问题结果
//        this----------2
//        is------------2
//        a-------------2
//        book----------1
//        that----------1
//        desk----------1
        String article = "this this is a book that is a desk";//问题的开始,问题的输入
        String[] words = article.split(" ");
        //Map<String,Integer> key保存的是单词,value保存的是该单词出现的次数
        Map<String,Integer> map = new HashMap<>();
        //this----2
        //考察单词数组中的每一个单词,
        for(int i = 0; i < words.length; i++)
        {
            //考察每一个单词,
            if(map.containsKey(words[i]))//如果map的key中存在该单词,将该单词出现的次数加1
            {
               int count = map.get(words[i]);
               count++;
               map.put(words[i],count);
            }
            else//如果map的key中不存在该单词,将该单词添加到map中
            {
                map.put(words[i],1);
            }
        }
        for(String word : map.keySet())
        {
            System.out.println(word+"--------"+map.get(word));
        }
    }

Set

和LIst类似,主要区别是不能保存重复元素

生成100000个UUID,判断是否有重复的?

Set<String> stringSetUUID = new HashSet<>();
        for(int i = 0; i < 10000000; i++)
        {
            UUID uuid = UUID.randomUUID();
            stringSetUUID.add(uuid.toString());
        }
        System.out.println(stringSetUUID.size());


扑克模拟问题续


随机发出5张牌,判断牌型


image.png

image.png

image.png

image.png


image.png

image.png


image.png

image.png


image.png

image.png

package com.company;
/**
 * Created by ttc on 2017/12/28.
 */
public class Card {
    private int value;//牌值
    private String color;//花色
    public Card(int value, String color) {
        this.value = value;
        this.color = color;
    }
    public int getValue() {
        return value;
    }
    public void setValue(int value) {
        this.value = value;
    }
    public String getColor() {
        return color;
    }
    public void setColor(String color) {
        this.color = color;
    }
    public String toString()
    {
        String str = "";
        if(value == 11)
        {
            str = "J";
        }
        else if(value == 12)
        {
            str = "Q";
        }
        else if(value == 13)
        {
            str = "K";
        }
        else if(value == 1)
        {
            str = "A";
        }
        else
        {
            str = value+"";
        }
        return color+str;
    }
}

package com.company;
import java.util.*;
/**
 * Created by ttc on 2017/12/28.
 */
public class Poker {
    List<Card> cards = new ArrayList<Card>();
    private String[] colors = {"红桃", "方片", "黑桃","草花"};
    private int[] values = {1,2,3,4,5,6,7,8,9,10,11,12,13};
    public Poker()
    {
        //初始化,创建52张扑克牌
        //红桃13张 1,2,3...
        //方片13张
        //外层循环生成花色
        //里层循环生成牌值
        for(int i = 0; i < colors.length; i++)
        {
            for(int j = 0; j < values.length; j++)
            {
                Card  card = new Card(values[j],colors[i]);
//                card.setColor(colors[i]);
//                card.setValue(values[j]);
                cards.add(card);
            }
        }
    }
    //洗牌方法
    public void shuffle()
    {
        Collections.shuffle(cards);
    }
    //打印扑克中的每一张牌
    public void output()
    {
        System.out.println(cards);
    }
    //发一手牌
    public List<Card> takeHands()
    {
        List<Card> cardList = new ArrayList<>();
        //把cards的前5张牌放到cardList里
        int count = 0;
        for(Card card : cards)
        {
            cardList.add(card);
            count++;
            if(count == 5)
            {
                break;
            }
        }
        return cardList;
    }
    //判断牌型
    public String judgeType(List<Card> cardList)
    {
        boolean isSameColor = false;//是否同花
        boolean isShunZi = false;//是否顺子
        String strType = "";
        Set<String> setColors = new HashSet<>();
        for(Card card : cardList)
        {
            setColors.add(card.getColor());
        }
        if(setColors.size() == 1)
        {
            isSameColor = true;
//            System.out.println("同花");
        }
        //5张牌,排好序,(最后一张减去第一张 == 4 && 把5张牌放到set中,set.size()== 5)
        Set<Integer> setValues = new HashSet<>();
        List<Integer> listValues = new ArrayList<>();
        for(Card card : cardList)
        {
            int value = card.getValue();
            setValues.add(value);
            listValues.add(value);
        }
        Collections.sort(listValues);
        int between = listValues.get(4) - listValues.get(0);
        if(between == 4 && setValues.size() == 5)
        {
            isShunZi = true;
//            System.out.println("顺子");
        }
        if(isSameColor == true && isShunZi == true)
        {
            strType = "同花顺";
//            System.out.println("同花顺");
        }
        else if(isSameColor == true)
        {
            strType = "同花";
//            System.out.println("同花");
        }
        else if(isShunZi == true)
        {
            strType = "顺子";
//            System.out.println("顺子");
        }
        else if(setValues.size() == 5)
        {
            strType = "杂牌";
//            System.out.println("杂牌");
        }
        else if(setValues.size() == 4)
        {
            strType = "一对";
//            System.out.println("一对");
        }
        else if(setValues.size() == 3)
        {
//            System.out.println("两对或3条");
//            System.out.println("四带一或三带二");
            Map<Integer, Integer> mapCardValue2Counts = new HashMap<>();
            //将5张牌从list结构转化到map中
            for(Card card: cardList)
            {
                //map的key中是否包含当前牌的值,如果包含,拿出当前牌值已经出现的次数
                if(mapCardValue2Counts.containsKey(card.getValue()))
                {
                    int count = mapCardValue2Counts.get(card.getValue());
                    count++;
                    mapCardValue2Counts.put(card.getValue(),count);
                }
                else//不包含
                {
                    mapCardValue2Counts.put(card.getValue(),1);
                }
            }
//            (9,3),(5,1),(3,1)
//            (13,2),(5,2),(2,1)
            for(Map.Entry<Integer, Integer> entry : mapCardValue2Counts.entrySet())
            {
                if(entry.getValue() == 3)
                {
                    strType = "三带一";
//                    System.out.println("三带一");
                    break;
                }
                else if(entry.getValue() == 2)
                {
                    strType = "两对";
//                    System.out.println("两对");
                    break;
                }
            }
        }
        else if(setValues.size() == 2)
        {
//            System.out.println("四带一或三带二");
            Map<Integer, Integer> mapCardValue2Counts = new HashMap<>();
            //将5张牌从list结构转化到map中
            for(Card card: cardList)
            {
                //map的key中是否包含当前牌的值,如果包含,拿出当前牌值已经出现的次数
                if(mapCardValue2Counts.containsKey(card.getValue()))
                {
                   int count = mapCardValue2Counts.get(card.getValue());
                   count++;
                   mapCardValue2Counts.put(card.getValue(),count);
                }
                else//不包含
                {
                    mapCardValue2Counts.put(card.getValue(),1);
                }
            }
//            (4,4),(9,1)
//            (3,3),(10,2)
            for(Map.Entry<Integer, Integer> entry : mapCardValue2Counts.entrySet())
            {
                if(entry.getValue() == 4)
                {
                    strType = "四带一";
//                    System.out.println("四带一");
                    break;
                }
                else if(entry.getValue() == 3)
                {
                    strType = "三带二";
//                    System.out.println("三带二");
                    break;
                }
            }
        }
        return strType;
    }
}

package com.company;
import java.util.ArrayList;
import java.util.List;
public class Main {
    public static void main(String[] args) {
    // write your code here
        Poker poker = new Poker();
        poker.output();
//        poker.shuffle();//洗牌
        System.out.println();
        poker.output();
//        List<Card> cardList = poker.takeHands();
        List<Card> cardList = new ArrayList<>();
        Card card = new Card(5,"黑桃");
        cardList.add(card);
        card = new Card(5,"红桃");
        cardList.add(card);
        card = new Card(9,"草花");
        cardList.add(card);
        card = new Card(8,"草花");
        cardList.add(card);
        card = new Card(8,"方片");
        cardList.add(card);
        System.out.println(cardList);
        String type = poker.judgeType(cardList);
        System.out.println(type);
    }
}


目录
相关文章
|
10月前
|
设计模式 安全
集合
集合
48 0
|
11月前
|
存储
|
存储 JavaScript 前端开发
集合的实现
集合的实现
集合的实现
|
存储 算法 安全
|
存储 Java 容器
|
存储 算法 安全
集合总结
集合总结
73 0
|
存储 安全 Java
第9章 集合
集合体系、集合的数据结构以及操作。
90 0
GoogleGuava - 第 2 章 集合——不可变集合
GoogleGuava - 第 2 章 集合——不可变集合
99 0
GoogleGuava - 第 2 章 集合——不可变集合
|
安全 Java
关于集合
NET有超过20种内置的集合类型,.NET Framework中有些集合只是为了保持向后兼容性,
102 0
关于集合