Java实例-集合

1、Java 实例 – 数组转集合:使用 Java Util 类的 Arrays.asList(name) 方法将数组转换为集合。

public class Collection_ArrayTo {

public Collection_ArrayTo()throws IOException {

int n =5;// 5 个元素

        String[] name =new String[n];

for(int i =0; i < n; i++){

name[i] = String.valueOf(i);

}

List list = Arrays.asList(name);

System.out.println("数组转集合:");

for(String li: list){

String str = li;

System.out.print(str +" ");

}

}

}

执行结果:

2、Java 实例 – 集合比较:将字符串转换为集合并使用 Collection 类的 Collection.min() 和 Collection.max() 来比较集合中的元素。

public class Collection_Compare {

public Collection_Compare() {

String[] coins = {"Penny","nickel","dime","Quarter","dollar" };

Set set =new TreeSet();

for (int i =0; i < coins.length; i++) {

set.add(coins[i]);

}

System.out.println("ASCII最小:"+Collections.min(set));//按照ASCII值大小排序

        System.out.println("ASCII最小(忽略大小写):"+Collections.min(set, String.CASE_INSENSITIVE_ORDER));//忽略字母的大小写

        System.out.println("````````````````````````");

System.out.println("ASCII最大:"+Collections.max(set));

System.out.println("ASCII最大(忽略大小写):"+Collections.max(set, String.CASE_INSENSITIVE_ORDER));

}

}

执行结果:

3、Java 实例 – HashMap遍历:使用 Collection 类的 iterator() 方法来遍历集合。

public class Collection_HashMap {//HashMap只遍历键值

    public Collection_HashMap() {

HashMap< String, String> hMap =

new HashMap< String, String>();

hMap.put("1","1st");

hMap.put("2","2nd");

hMap.put("3","3rd");

Collection cl = hMap.values();

Iterator itr = cl.iterator();

while (itr.hasNext()) {

System.out.println(itr.next());

}

}

}

执行结果:

4、Java 实例 – 集合长度:使用 Collections 类 的collection.add() 来添加数据并使用 collection.size()来计算集合的长度。

public class Collection_GetLength {

public Collection_GetLength() {

System.out.println("集合实例!\n" );

int size;

HashSet collection =new HashSet ();

String str1 ="Yellow", str2 ="White", str3 =

"Green", str4 ="Blue";

Iterator iterator;

collection.add(str1);

collection.add(str2);

collection.add(str3);

collection.add(str4);

System.out.print("集合数据: ");

iterator = collection.iterator();

while (iterator.hasNext()){

System.out.print(iterator.next() +" ");

}

System.out.println();

size = collection.size();

if (collection.isEmpty()){

System.out.println("集合是空的");

}

else{

System.out.println("集合长度: " + size);

}

System.out.println();

}

}

执行结果:

5、Java 实例 – 集合打乱顺序:使用 Collections 类 Collections.shuffle() 方法来打乱集合元素的顺序。

public class Collection_Disorganize {

public Collection_Disorganize() {

List list =new ArrayList();

for (int i =0; i <10; i++)

list.add(new Integer(i));

System.out.println("原集合:");

System.out.println(list);

for (int i =1; i <3; i++) {

System.out.println("第" + i +"次打乱:");

Collections.shuffle(list);

System.out.println(list);

}

}

}

执行结果:

6、Java 实例 – 集合遍历:遍历从Collection接口延伸出的List、Set和以键值对形式作存储的Map类型的集合,以下分别使用普通for,增强型的 for ,iterator 等方式来遍历集合。

public class Collection_Ergodic {

public Collection_Ergodic() {

// List集合的遍历

        listTest();

// Set集合的遍历

        setTest();

}

private static void setTest() {

Set set =new HashSet();

set.add("JAVA");

set.add("C");

set.add("C++");

// 重复数据添加失败

        set.add("JAVA");

set.add("JAVASCRIPT");

// 使用iterator遍历set集合

        Iterator it = set.iterator();

System.out.println("\nSet集合迭代器遍历:");

while (it.hasNext()) {

String value = it.next();

System.out.print(value+"  ");

}

// 使用增强for循环遍历set集合

        System.out.println("\nSet集合增强for循环遍历:");

for(String s: set){

System.out.print(s+"  ");

}

}

// 遍历list集合

    private static void listTest() {

List list =new ArrayList();

list.add("A");

list.add("B");

list.add("C");

list.add("D");

// 使用iterator遍历

        Iterator it = list.iterator();

System.out.println("List集合迭代器遍历:");

while (it.hasNext()) {

String value = it.next();

System.out.print(value+"  ");

}

// 使用传统for循环进行遍历

        System.out.println("\nList集合传统for循环遍历:");

for (int i =0, size = list.size(); i < size; i++) {

String value = list.get(i);

System.out.print(value+"  ");

}

// 使用增强for循环进行遍历

        System.out.println("\nList集合增强for循环遍历:");

for (String value : list) {

System.out.print(value+"  ");

}

}

}

执行结果:

7、Java 实例 – 集合反转:使用 Collection 和 Listiterator 类的 listIterator() 和 collection.reverse() 方法来反转集合中的元素。

public class Collection_Reverse {

public Collection_Reverse() {

String[] coins = {"A","B","C","D","E" };

List l =new ArrayList();

for (int i =0; i < coins.length; i++)

l.add(coins[i]);

ListIterator liter = l.listIterator();

System.out.println("反转前");

while (liter.hasNext())

System.out.print(liter.next()+"  ");

Collections.reverse(l);

liter = l.listIterator();

System.out.println("\n反转后");

while (liter.hasNext())

System.out.print(liter.next()+"  ");

}

}

执行结果:

8、Java 实例 – 删除集合中指定元素:使用 Collection 类的 collection.remove() 方法来删除集合中的指定的元素。

public class Collection_Delete {

public Collection_Delete() {

System.out.println("集合实例!\n" );

int size;

HashSet collection =new HashSet ();

String str1 ="Yellow", str2 ="White", str3 =

"Green", str4 ="Blue";

Iterator iterator;

collection.add(str1);

collection.add(str2);

collection.add(str3);

collection.add(str4);

System.out.print("集合数据: ");

iterator = collection.iterator();

while (iterator.hasNext()){

System.out.print(iterator.next() +" ");

}

System.out.println();

collection.remove(str2);

System.out.println("删除 [" + str2 +"]\n");

System.out.print("当前集合的数据是: ");

iterator = collection.iterator();

while (iterator.hasNext()){

System.out.print(iterator.next() +" ");

}

System.out.println();

size = collection.size();

System.out.println("集合大小: " + size +"\n");

}

}

执行结果:

9、Java 实例 – 只读集合:使用 Collection 类的 Collections.unmodifiableList() 方法来设置集合为只读。

public class Collection_OnlyRead {

public Collection_OnlyRead()throws Exception {

List stuff = Arrays.asList(new String[] {"a","b" });

List list =new ArrayList(stuff);

list = Collections.unmodifiableList(list);

try {

list.set(0,"new value");

}

catch (UnsupportedOperationException e) {

}

Set set =new HashSet(stuff);

set = Collections.unmodifiableSet(set);

Map map =new HashMap();

map = Collections.unmodifiableMap(map);

System.out.println("只读集合");

}

}

执行结果:

10、Java 实例 – 集合输出:使用 Java Util 类的 tMap.keySet(),tMap.values() 和 tMap.firstKey() 方法将集合元素输出。

public class Collection_Print {

public Collection_Print() {

TreeMap tMap =new TreeMap();

tMap.put(1,"Sunday");

tMap.put(2,"Monday");

tMap.put(3,"Tuesday");

tMap.put(4,"Wednesday");

tMap.put(5,"Thursday");

tMap.put(6,"Friday");

tMap.put(7,"Saturday");

System.out.println("TreeMap 键:"

                + tMap.keySet());

System.out.println("TreeMap 值:"

                + tMap.values());

System.out.println("键为 5 的值为: " + tMap.get(5));

System.out.println("第一个键: " + tMap.firstKey()

+" Value: "

                + tMap.get(tMap.firstKey()));

System.out.println("最后一个键: " + tMap.lastKey()

+" Value: "+ tMap.get(tMap.lastKey()));

System.out.println("移除第一个数据: "

                + tMap.remove(tMap.firstKey()));

System.out.println("现在 TreeMap 键为: "

                + tMap.keySet());

System.out.println("现在 TreeMap 包含: "

                + tMap.values());

System.out.println("移除最后一个数据: "

                + tMap.remove(tMap.lastKey()));

System.out.println("现在 TreeMap 键为: "

                + tMap.keySet());

System.out.println("现在 TreeMap 包含: "

                + tMap.values());

}

}

执行结果:

11、Java 实例 – 集合转数组:Java Util 类的 list.add() 和 list.toArray() 方法将集合转为数组。

public class Collection_ToArray {

public Collection_ToArray(){

List list =new ArrayList();

list.add("A");

list.add("B");

list.add("C");

list.add("D");

String[] s1 = list.toArray(new String[0]);

for(int i =0; i < s1.length; ++i){

String contents = s1[i];

System.out.print(contents+"  ");

}

}

}

执行结果:

12、Java 实例 – List 循环移动元素:使用 Collections 类的 rotate() 来循环移动元素,方法第二个参数指定了移动的起始位置。

public class Collection_Rotate {

public Collection_Rotate() {

List list = Arrays.asList("one Two three Four five six".split(" "));

System.out.println("List :"+list);

Collections.rotate(list,3);

System.out.println("rotate: " + list);

}

}

执行结果:

13、Java 实例 – 查找 List 中的最大最小值:使用 Collections 类的 max() 和 min() 方法来获取List中最大最小值。

public class Collection_ListMaxMin {

public Collection_ListMaxMin() {

List list = Arrays.asList("one Two three Four five six one three Four".split(" "));

System.out.println(list);

System.out.println("最大值: " + Collections.max(list));

System.out.println("最小值: " + Collections.min(list));

}

}

执行结果:

14、Java 实例 – 遍历 HashTable 的键值:使用 Hashtable 类的 keys() 方法来遍历输出键值。

public class Collection_HashTableKeys {

public Collection_HashTableKeys() {

Hashtable ht =new Hashtable();

ht.put("1","One");

ht.put("2","Two");

ht.put("3","Three");

Enumeration e = ht.keys();

System.out.println("HashTable的键值:");

while (e.hasMoreElements()){

System.out.println(e.nextElement());

}

}

}

执行结果:

15、Java 实例 – 集合中添加不同类型元素:

public class Collection_Add {

public Collection_Add() {

List lnkLst =new LinkedList();

lnkLst.add("element1");

lnkLst.add("element2");

lnkLst.add("element3");

lnkLst.add("element4");

displayAll(lnkLst);

List aryLst =new ArrayList();

aryLst.add("x");

aryLst.add("y");

aryLst.add("z");

aryLst.add("w");

displayAll(aryLst);

Set hashSet =new HashSet();

hashSet.add("set1");

hashSet.add("set2");

hashSet.add("set3");

hashSet.add("set4");

displayAll(hashSet);

SortedSet treeSet =new TreeSet();

treeSet.add("1");

treeSet.add("2");

treeSet.add("3");

treeSet.add("4");

displayAll(treeSet);

LinkedHashSet lnkHashset =new LinkedHashSet();

lnkHashset.add("one");

lnkHashset.add("two");

lnkHashset.add("three");

lnkHashset.add("four");

displayAll(lnkHashset);

Map map1 =new HashMap();

map1.put("key1","J");

map1.put("key2","K");

map1.put("key3","L");

map1.put("key4","M");

displayAll(map1.keySet());

displayAll(map1.values());

SortedMap map2 =new TreeMap();

map2.put("key1","JJ");

map2.put("key2","KK");

map2.put("key3","LL");

map2.put("key4","MM");

displayAll(map2.keySet());

displayAll(map2.values());

LinkedHashMap map3 =new LinkedHashMap();

map3.put("key1","JJJ");

map3.put("key2","KKK");

map3.put("key3","LLL");

map3.put("key4","MMM");

displayAll(map3.keySet());

displayAll(map3.values());

}

static void displayAll(Collection col) {

Iterator itr = col.iterator();

while (itr.hasNext()) {

String str = (String) itr.next();

System.out.print(str +" ");

}

System.out.println();

}

}

执行结果:

16、Java 实例 – List 元素替换:使用 Collections 类的 replaceAll() 来替换List中所有的指定元素。

public class Collection_Replace {

public Collection_Replace() {

List list = Arrays.asList("one Two three Four five six one three Four".split(" "));

System.out.println("List :"+list);

Collections.replaceAll(list,"one","hundred");

System.out.println("one替换成hundred: " + list);

}

}

执行结果:

17、Java 实例 – List 截取:使用 Collections 类的 indexOfSubList() 和 lastIndexOfSubList() 方法来查看子列表是否在列表中,并查看子列表在列表中所在的位置。

public class Collection_Cut {

public Collection_Cut() {

List list = Arrays.asList("one Two three Four five six one three Four".split(" "));

System.out.println("List :"+list);

List sublist = Arrays.asList("three Four".split(" "));

System.out.println("子列表 :"+sublist);

System.out.println("indexOfSubList: "

                + Collections.indexOfSubList(list, sublist));

System.out.println("lastIndexOfSubList: "

                + Collections.lastIndexOfSubList(list, sublist));

}

}

执行结果:

你可能感兴趣的:(Java实例-集合)