Skip to content

nekman/Sequence

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

41 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

###Sequence

Util class for Java collections inspired by LINQ in C# - http://msdn.microsoft.com/en-us/library/bb341635.aspx
There are other libraries out there that can be used to querying collections e.g:
LambdaJ
TinyQ

This project aims to match the LINQ -syntax.

###Build status Build Status

###Quick example Generate a sequence of numbers

Integer[] numbers = from().range(1, 5).take(4).toArray(); //[1, 2, 3, 4]

Select all names from a Person collection.

from(persons).select(new Func<Person, String>() {
  public String map(Person p) {
    return p.getName();
  }
})
.take(10); //First 10 person names in the collection.

See more examples bellow.

###Supported methods

from(Collection)
from(T...)
concat(Collection)
concat(T...)
any()
any(Predicate)
all(Predicate)
filter(Predicate)
where(Predicate)
map(Func<T, TResult>)
select(Func<T, TResult>)
skip(int)
take(int)
count()
last()
lastOrDefault()
first()
firstOrDefault()
range(int, int)
toList()
toCollection()
toArray()
toSet()
forEach(Action)
ofType(Class)

Example of map and filter

###Initialization

For easiest access, import the 'from' method static:

import static se.nekman.sequence.Sequence.from;

Can also be created using the constructor:

Sequence<String> sequence = new Sequence<String>(Arrays.asList("foo", "bar"));

#####from()

  from(1,2,3,4,5)
    .take(2)
    .last(); //2 
    
  from(1,2,3,4,5)
    .skip(2)
    .first(); //3

  from().range(1,5) // [1, 2, 3, 4, 5]

  List<Person> persons = Arrays.asList(new Person());
  boolean hasPersons = from(persons).any(); //true
  
  String[] names = { "adam", "ben", "ceasar" };
  from(names)
    .take(2)  // ["adam", "ben"]
    .first(); // "adam"

#####concat()

Concatenates two sequences.

   from(1,2,3)
      .concat(4,5)
      .toArray(); //[1, 2, 3, 4, 5]

   Person[] persons = from(persons)
                .concat(getOtherPersons())
                .toArray();

#####any()

Determines whether a sequence contains any elements.

   List<Integer> numbers = getNumbers();
   if (from(numbers).any()) {
      // Sequence contain elements
   }
  
   Sequence<Integer> ids = from(getIds());
   if (ids.any()) {
      // Sequence contain elements
   }
   
   Predicate<Person> namesStartsWithA = new Predicate<Person>() {
      public boolean match(Person p) {
         return p.getName().startsWith("a");
      }
   };
   
   if (from(getPersons()).any(namesStartsWithA)) {
      // Sequence contains persons with names that starts with "a"
   }

#####all()

Determines whether all elements of a sequence satisfy a predicate.

 
  Predicate<Person> isOlderThan30 = new Predicate<Person>() {
     public boolean match(Person p) {
        return p.getAge() > 30;
     }
  };

 boolean allPersonsIsOlderThan30 = from(getPersons()).all(isOlderThan30);

#####filter() / where() Filters a sequence of values based on a predicate.

Note: filter is same as where.

  Predicate<Person> oldPersons = new Predicate<Person>() {
     public boolean match(Person p) {
        return p.getAge() > 70;
     }
  };
  
  List<Person> persons = getPersons();
  
  // has old persons?  
  boolean hasOldPersons = from(persons)    
    .filter(oldPersons)
    .any();

#####map() / select()

Projects each element of a sequence into a new form.

Note: map is same as select.

  Func<Person, Integer> getShoeSizes = new Func<Person, Integer() {
      public int map(Person p) {
        return p.getShoeSize();
      }
  };

  Integer[] shoeSizes = from(persons)
     .map(getShoeSizes)
     .toArray();

#####skip()

    from(getPersons())
       .skip(5) // Skip the first five persons in the sequence
       
    from(1, 2, 3, 4, 5)
       .skip(2) // [3, 4, 5]

#####take()

    from(getPersons())
       .take(5) // Take the first five persons in the sequence
       
    from(1, 2, 3, 4, 5)
       .take(2) // [1, 2]

#####count()

Gets the number of elements in the sequence.

    int numberOfPersons = from(getPersons()).count();       

#####last()

Gets the last element of a sequence. Throws a EmptySequenceException if the sequence is empty.

    from("foo", "bar", "baz").last(); // "baz" 

    from("foo", "bar", "baz").skip(4).last(); // throws EmptySequenceException   

#####lastOrDefault()

Gets the last element of a sequence, or default if the sequence is empty.

    from("foo", "bar", "baz").lastOrDefault(); // "baz" 

    from("foo", "bar", "baz").skip(4).lastOrDefault(); // null

#####first()

Gets the first element of a sequence. Throws a EmptySequenceException if the sequence is empty.

    from("foo", "bar", "baz").first(); // "foo" 

    from("foo", "bar", "baz").skip(4).first(); // throws EmptySequenceException   

#####firstOrDefault()

Gets the first element of a sequence, or default if the sequence is empty.

    from("foo", "bar", "baz").firstOrDefault(); // "foo" 

    from("foo", "bar", "baz").skip(4).firstOrDefault(); // null

#####range(int, int)

Generates a sequence of integral numbers within a specified range.

    from().range(1, 3); //[1, 2, 3]

    from().range(1, 1000); //[1, 2, 3, ... , 1000]    

#####toList()

Returns the sequence as an List.

    List<Person> persons = from(getPersons()).take(5).toList();

    Person[] persons = from(getPersons()).take(5).toArray();

    Collection<Person> persons = from(getPersons()).take(5).toCollection();

    Set<String> persons = from("foo", "foo", "bar", "bar").toSet(); //["foo", "bar"]

#####forEach()

Performs the specified action on each element in the sequence.

  //Create a action
  Action<Person> updatePersonAge = new Action<Person>() {    
    public void execute(Person p) {
      p.age += 10;
    }           
  };

  from(getPersons()).forEach(updatePersonAge);

#####ofType()

Filters the elements of an sequence based on a specified type.

// Get all properties (Hashtable<Object,Object>)
Properties props = getProperties();

for (String s : from(props.keySet()).ofType(String.class)) {
    // Do something with the string
}

#####Filter/Where Map/Select examples

Note that the filter and map function is equal to select and where.

  //Select function
  Func<Person, String> personName = new Func<Person, String>() {    
    public String map(Person p) {
      return p.getName();
    }           
  };
  
  //Where predicate
  Predicate<String> hasLongNames = new Predicate<String>() {
     public boolean match(String s) {
        return s.length() > 10;
     }
  };
  
  // All persons with long names
  String[] personWithLongNames = from(getPersons())
              .concat(getOtherPersons())
              .select(personName)
              .where(hasLongNames)
              .toArray();
              
  // First five with long names         
  List<String> firstFive = from(personWithLongNames)
              .take(5)
              .toList();
                
  // Sequence of strings
  Sequence<String> seq = from(firstFive);
  
  boolean hasElementsInSequence = seq.any();  
  String first = seq.firstOrDefault();
  String last = seq.lastOrDefault();
  

About

Helper classes that makes it easier to work with collections in Java.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages