org.apache.commons.collections4.set.ListOrderedSet Example

Q

What is org.apache.commons.collections4.set.ListOrderedSet class? How to use org.apache.commons.collections4.set.ListOrderedSet class?

✍: FYIcenter.com

A

org.apache.commons.collections4.set.ListOrderedSet class is a Java class offered in commons-collections4.jar that wraps a regular map into a special map with a list to maintain the order of when objects are added to the set.

If an object is added to the set for a second time, it will remain in the original position in the iteration. The order can be observed from the set via the iterator or toArray methods.

The ListOrderedSet also has various useful direct methods. These include many from List, such as get(int), remove(int) and indexOf(int). An unmodifiable List view of the set can be obtained via asList().

Here is a simple example of using org.apache.commons.collections4.bag.HashBag class:

// Copyright (c) 2016 FYIcenter.com
import java.util.Set;
import org.apache.commons.collections4.set.ListOrderedSet;

// Example of using the ListOrderedSetExample class
public class ListOrderedSetExample {
   public static void main(String[] args) throws Exception {

      // Create some objects
      String apple = "Apple";
      String orange = "Orange";
      String banana = "Banana";

      // Create a ListOrderedSet set
      ListOrderedSet<String> set = new ListOrderedSet<String>();
      
      // Put some objects into the ListOrderedSet set
      set.add(apple);
      set.add(orange);
      set.add(apple);
      set.add(orange);
      set.add(apple);
      set.add(banana);

      // loop through the set as a list
      for (int i=0; i<3; i++) {
         String obj = set.get(i);
         System.out.println(i+": " + obj);
      }
   }
}

You can compile and run the above example in a command window as shown below:

C:\fyicenter>\local\jdk-1.7.0\bin\javac 
   -cp C:\local\commons-collections4-4.1\commons-collections4-4.1.jar 
   ListOrderedSetExample.java

C:\fyicenter>\local\jdk-1.7.0\bin\java
   -cp .;C:\local\commons-collections4-4.1\commons-collections4-4.1.jar 
   ListOrderedSetExample

0: Apple
1: Orange
2: Banana

 

Using commons-collections.jar in Java Programs

⇒⇒FAQ for Apache commons-collections.jar

2017-05-20, 403👍, 0💬