Java/Collections Data Structure/Collections
Содержание
- 1 Collections.fill
- 2 Collections.min with Comparator
- 3 Collections.reverse
- 4 Collections.shuffle to shuffle a list
- 5 Create and demonstrate an immutable collection.
- 6 Create an empty collection object
- 7 Create List containing n Copies of Specified Object Example
- 8 Demonstrates the use of final collections
- 9 Making a Collection Read-Only
- 10 Minimum and maximum number in array
- 11 Shuffle generic list
- 12 Shuffle the elements in the array
- 13 Shuffling the Elements of a List or Array: use Collections.shuffle() to randomly reorder the elements in a list
- 14 Sort and Search a LinkedList.
- 15 Use Collections.shuffle to shuffle list
- 16 Use Collections.sort to sort custom class and user defined Comparator
- 17 Use reverse(), rotate(), and shuffle().
Collections.fill
<source lang="java">
import java.util.ArrayList; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.ListIterator; class MainClass {
public static void main(String[] args) { String[] coins = { "A", "B", "C", "D", "E" }; List src = new LinkedList(); for (int i = 0; i < coins.length; i++) src.add(coins[i]); List dst = new ArrayList(); for (int i = 0; i < coins.length; i++) dst.add(""); Collections.copy(dst, src); ListIterator liter = dst.listIterator(); while (liter.hasNext()) System.out.println(liter.next()); Collections.fill(src, "no coins"); liter = src.listIterator(); while (liter.hasNext()) System.out.println(liter.next()); }
}
</source>
Collections.min with Comparator
<source lang="java">
import java.util.Collections; import java.util.Set; import java.util.TreeSet; class MainClass {
public static void main(String[] args) { 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(Collections.min(set)); System.out.println(Collections.min(set, String.CASE_INSENSITIVE_ORDER)); System.out.println(""); System.out.println(Collections.max(set)); System.out.println(Collections.max(set, String.CASE_INSENSITIVE_ORDER)); }
}
</source>
Collections.reverse
<source lang="java">
import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.ListIterator; class UtilDemo3 {
public static void main(String[] args) { 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(); while (liter.hasNext()) System.out.println(liter.next()); Collections.reverse(l); liter = l.listIterator(); while (liter.hasNext()) System.out.println(liter.next()); }
}
</source>
Collections.shuffle to shuffle a list
<source lang="java">
import java.util.Arrays; import java.util.Collections; import java.util.List; public class MainClass {
public static void main(String[] args) { List<String> argList = Arrays.asList(args); Collections.shuffle(argList); for (String arg : argList) { System.out.format("%s ", arg); } System.out.println(); }
}
</source>
Create and demonstrate an immutable collection.
<source lang="java">
import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; public class Main {
public static void main(String args[]) { List<Character> list = new ArrayList<Character>(); list.add("X"); System.out.println("Element added to list: " + list.get(0)); Collection<Character> immutableCol = Collections.unmodifiableCollection(list); immutableCol.add("Y"); }
}
</source>
Create an empty collection object
<source lang="java">
import java.util.Collections; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Set; public class Main {
public static void main(String args[]) { List list = Collections.EMPTY_LIST; Set set = Collections.EMPTY_SET; Map map = Collections.EMPTY_MAP; List<String> s = Collections.emptyList(); Set<Long> l = Collections.emptySet(); Map<Date, String> d = Collections.emptyMap(); }
}
</source>
Create List containing n Copies of Specified Object Example
<source lang="java">
import java.util.Collections; import java.util.Iterator; import java.util.List; public class Main {
public static void main(String[] args) { List list = Collections.nCopies(5, "A"); Iterator itr = list.iterator(); while (itr.hasNext()) System.out.println(itr.next()); }
} /* A A A A A
- /
</source>
Demonstrates the use of final collections
<source lang="java">
/*
* file: FinalCollections.java * package: oreilly.hcj.finalstory * * This software is granted under the terms of the Common Public License, * CPL, which may be found at the following URL: * http://www-124.ibm.ru/developerworks/oss/CPLv1.0.htm * * Copyright(c) 2003-2005 by the authors indicated in the @author tags. * All Rights are Reserved by the various authors. * ########## DO NOT EDIT ABOVE THIS LINE ########## */
import java.awt.Color; import java.util.Collections; import java.util.HashSet; import java.util.Set; /**
* Demonstrates the use of final collections. * * @author * @version $Revision: 1.3 $ */ public static class RainbowBetter { /** The valid colors of the rainbow. */ public static final Set VALID_COLORS; static { Set temp = new HashSet(); temp.add(Color.red); temp.add(Color.orange); temp.add(Color.yellow); temp.add(Color.green); temp.add(Color.blue); temp.add(Color.decode("#4B0082")); // indigo temp.add(Color.decode("#8A2BE2")); // violet VALID_COLORS = Collections.unmodifiableSet(temp); } /** * Some demo method. */ public static final void someMethod() { Set colors = RainbowBetter.VALID_COLORS; colors.add(Color.black); // <= exception here System.out.println(colors); } }
} /* ########## End of File ########## */
</source>
Making a Collection Read-Only
<source lang="java">
import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; public class Main {
public static void main(String[] argv) 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); }
}
</source>
Minimum and maximum number in array
<source lang="java">
import java.util.Arrays; import java.util.Collections; public class Main {
public static void main(String[] args) { Integer[] numbers = { 8, 2, 6, 7, 0, 1, 4, 9, 5, 3 }; int min = (int) Collections.min(Arrays.asList(numbers)); int max = (int) Collections.max(Arrays.asList(numbers)); System.out.println("Min number: " + min); System.out.println("Max number: " + max); }
}
</source>
Shuffle generic list
<source lang="java">
/*
* Copyright (c) 1995 - 2008 Sun Microsystems, Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of Sun Microsystems nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
import java.util.ArrayList; import java.util.Collections; import java.util.List; public class Deal {
public static void main(String[] args) { if (args.length < 2) { System.out.println("Usage: Deal hands cards"); return; } int numHands = Integer.parseInt(args[0]); int cardsPerHand = Integer.parseInt(args[1]); List<Card> deck = Deck.newDeck(); Collections.shuffle(deck); if (numHands * cardsPerHand > deck.size()) { System.out.println("Not enough cards."); return; } for (int i = 0; i < numHands; i++) System.out.println(dealHand(deck, cardsPerHand)); } public static ArrayList<Card> dealHand(List<Card> deck, int n) { int deckSize = deck.size(); List<Card> handView = deck.subList(deckSize - n, deckSize); ArrayList<Card> hand = new ArrayList<Card>(handView); handView.clear(); return hand; }
} /*
* Copyright (c) 1995 - 2008 Sun Microsystems, Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * - Neither the name of Sun Microsystems nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */
class Card {
private final Rank rank; private final Suit suit; public Card(Rank rank, Suit suit) { this.rank = rank; this.suit = suit; } public Rank rank() { return rank; } public Suit suit() { return suit; } public String toString() { return rank + " of " + suit; }
} /*
* Copyright (c) 1995 - 2008 Sun Microsystems, Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * - Neither the name of Sun Microsystems nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */
class Deck {
private static final List<Card> protoDeck = new ArrayList<Card>(); // Initialize prototype deck static { for (Suit suit : Suit.values()) for (Rank rank : Rank.values()) protoDeck.add(new Card(rank, suit)); } public static ArrayList<Card> newDeck() { // Return copy of prototype deck return new ArrayList<Card>(protoDeck); } public static void main(String[] args) { System.out.println(newDeck()); }
} /*
* Copyright (c) 1995 - 2008 Sun Microsystems, Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * - Neither the name of Sun Microsystems nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */
enum Suit {
CLUBS, DIAMONDS, HEARTS, SPADES
} /*
* Copyright (c) 1995 - 2008 Sun Microsystems, Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * - Neither the name of Sun Microsystems nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */
enum Rank {
DEUCE, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING, ACE
}
</source>
Shuffle the elements in the array
<source lang="java">
import java.util.Arrays; import java.util.Collections; public class Main {
public static void main(String[] argv) throws Exception { String[] array = new String[] { "a", "b", "c" }; Collections.shuffle(Arrays.asList(array)); }
}
</source>
Shuffling the Elements of a List or Array: use Collections.shuffle() to randomly reorder the elements in a list
<source lang="java">
import java.util.ArrayList; import java.util.Collections; import java.util.List; public class Main {
public static void main(String[] argv) throws Exception { List list = new ArrayList(); Collections.shuffle(list); }
}
</source>
Sort and Search a LinkedList.
<source lang="java">
import java.util.Collections; import java.util.LinkedList; import java.util.List; public class Main {
public static void main(String args[]) { List<Character> ll = new LinkedList<Character>(); for (char n = "A"; n <= "Z"; n++) ll.add(n); Collections.shuffle(ll); for (Character x : ll) System.out.print(x + " "); Collections.sort(ll); for (Character x : ll) System.out.print(x + " "); System.out.println("Searching for F."); int i = Collections.binarySearch(ll, "F"); if (i >= 0) { System.out.println("Found at index " + i); System.out.println("Object is " + ll.get(i)); } }
}
</source>
Use Collections.shuffle to shuffle list
<source lang="java">
/*
* Copyright (c) 1995 - 2008 Sun Microsystems, Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of Sun Microsystems nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
import java.util.Arrays; import java.util.Collections; import java.util.List; public class Shuffle {
public static void main(String[] args) { List<String> list = Arrays.asList(args); Collections.shuffle(list); System.out.println(list); }
}
</source>
Use Collections.sort to sort custom class and user defined Comparator
<source lang="java">
import java.util.ArrayList; import java.util.Collections; import java.util.ruparator; import java.util.List; import java.util.ListIterator; class Employee implements Comparable {
private String name; private double salary; Employee(String name, double salary) { this.name = name; this.salary = salary; } String getName() { return name; } double getSalary() { return salary; } public String toString() { return "Name = " + getName() + ", Salary = " + getSalary(); } public int compareTo(Object o) { if (!(o instanceof Employee)) throw new ClassCastException(); Employee e = (Employee) o; return name.rupareTo(e.getName()); } static class SalaryComparator implements Comparator { public int compare(Object o1, Object o2) { if (!(o1 instanceof Employee) || !(o2 instanceof Employee)) throw new ClassCastException(); Employee e1 = (Employee) o1; Employee e2 = (Employee) o2; return (int) (e1.getSalary() - e2.getSalary()); } }
} class UtilDemo4 {
public static void main(String[] args) { String[] names = { "A", "B", "C", "D" }; double[] salaries = { 2.0, 5.0, 6.0, 4.0 }; List l = new ArrayList(); for (int i = 0; i < names.length; i++) l.add(new Employee(names[i], salaries[i])); Collections.sort(l); ListIterator liter = l.listIterator(); while (liter.hasNext()) System.out.println(liter.next()); Collections.sort(l, new Employee.SalaryComparator()); liter = l.listIterator(); while (liter.hasNext()) System.out.println(liter.next()); }
}
</source>
Use reverse(), rotate(), and shuffle().
<source lang="java">
import java.util.Collections; import java.util.LinkedList; import java.util.List; public class Main {
public static void main(String args[]) { List<Character> ll = new LinkedList<Character>(); for (char n = "A"; n <= "F"; n++) ll.add(n); System.out.println("Here is the original list: "); for (Character x : ll) System.out.print(x + " "); Collections.reverse(ll); System.out.println("Here is the reversed list: "); for (Character x : ll) System.out.print(x + " "); Collections.rotate(ll, 2); for (Character x : ll) System.out.print(x + " "); Collections.shuffle(ll); System.out.println("Here is the randomized list:"); for (Character x : ll) System.out.print(x + " "); }
}
</source>