java api集合,javaAPI_集合基础_集合中常见操作示例
集合中常見的操作
1.list集合去重
//使用HashSet去重
public static List removeDuplicate(List list) {
HashSet h = new HashSet(list);
list.clear();
list.addAll(h);
return list;
}
其他內容待添加
一個集合操作(Collections類操作)的綜合案例:(模擬斗地主)
package com.cn.collectiontool;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.TreeSet;
/*
* 思路:
* A:創建一個HashMap集合
* B:創建一個ArrayList集合
* C:創建花色數組和點數數組
* D:從0開始往HashMap里面存儲編號,并存儲對應的牌
* 同時往ArrayList里面存儲編號即可。
* E:洗牌(洗的是編號)
* F:發牌(發的也是編號,為了保證編號是排序的,就創建TreeSet集合接收)
* G:看牌(遍歷TreeSet集合,獲取編號,到HashMap集合找對應的牌)
*/
public class PokerDemo {
public static void main(String[] args) {
// 創建一個HashMap集合
HashMap hm = new HashMap();
// 創建一個ArrayList集合
ArrayList array = new ArrayList();
// 創建花色數組和點數數組
// 定義一個花色數組
String[] colors = { "?", "?", "?", "?" };
// 定義一個點數數組
String[] numbers = { "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q",
"K", "A", "2", };
// 從0開始往HashMap里面存儲編號,并存儲對應的牌,同時往ArrayList里面存儲編號即可。
int index = 0;
for (String number : numbers) {
for (String color : colors) {
String poker = color.concat(number);
hm.put(index, poker);
array.add(index);
index++;
}
}
hm.put(index, "小王");
array.add(index);
index++;
hm.put(index, "大王");
array.add(index);
// 洗牌(洗的是編號)
Collections.shuffle(array);
// 發牌(發的也是編號,為了保證編號是排序的,就創建TreeSet集合接收)
TreeSet fengQingYang = new TreeSet();
TreeSet linQingXia = new TreeSet();
TreeSet liuYi = new TreeSet();
TreeSet diPai = new TreeSet();
for (int x = 0; x < array.size(); x++) {
if (x >= array.size() - 3) {
diPai.add(array.get(x));
} else if (x % 3 == 0) {
fengQingYang.add(array.get(x));
} else if (x % 3 == 1) {
linQingXia.add(array.get(x));
} else if (x % 3 == 2) {
liuYi.add(array.get(x));
}
}
// 看牌(遍歷TreeSet集合,獲取編號,到HashMap集合找對應的牌)
lookPoker("張三", fengQingYang, hm);
lookPoker("李四", linQingXia, hm);
lookPoker("王五", liuYi, hm);
lookPoker("底牌", diPai, hm);
}
// 寫看牌的功能 public static void lookPoker(String name, TreeSet ts, HashMap hm) { System.out.print(name + "的牌是:"); for (Integer key : ts) { String value = hm.get(key); System.out.print(value + " "); } System.out.println(); }}
總結
以上是生活随笔為你收集整理的java api集合,javaAPI_集合基础_集合中常见操作示例的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: hibernate连接mysql密码错误
- 下一篇: twig模板引擎使用php,Twig模板