Sequences are like arrays and hold a collection of object. The ordering is associated with the objects in the sequence.
Different way of defining sequences:
//Sequence of String with double quotes
def seq1 = ["JavaFX" , "Silverlight" , "Flash"];
//Sequence of String with single quote
def seq2 = [ 'JavaFX', 'Silverlight', 'Flash'];
//Sequence of String with embedded sequence
def seq3 = [["JavaFX" , [["Silverlight", "Flash"]];
//Sequence of Integers. The type is inferred automatically
def seq4 = [1,2,3,4];
//Sequence of series. The sequence will contain 1,2,3,4,5
def seq5 = [1..5];
//Sequence with type explicitly mentioned. seq6 contains Integer type.
def seq6 : Integer[] = [1..5];
//Sequence defined as a var
var seq7 : String[];
Sequences are immutable in nature. Values can be changed but any insertion or deletions results in a new sequence.
Accessing Sequence
Sequence can be accessed using index position starting at 0. Also embedded sequence are flattened.
//Sequence contains and embedded sequence
def seq = [["JavaFX" , [["Silverlight", "Flash"]];
//Sequence accessed in ordinal way, we do not access "Silverlight" as seq10
print(seq[0]);
print(seq[1]);
print(seq[2]);
Accessing sequence in a loop.
//Sequence
def seq = ["JavaFX" ,"Silverlight", "Flash"];
//Accessed in a loop
for(value in seq){
print(value);
}
sizeof operator tells the size of sequence
println(sizeof seq);
Operation on Sequence
Insertion
//Start with a sequence. We are using var here as we will be modifying it.
var seq = ["JavaFX"];
//Insert into sequence
insert "Silverlight" into seq;
//Insert before a certain position in sequence
insert "Flash" before seq[1];
//Insert after a certain position in sequence.
insert "Swing" after seq[2];
//Print the sequence
for(value in seq){
println(value);
}
Deletion
//Delete based on value
delete "Swing" from seq;
//Delete index
delete seq[2];
//Delete the sequence
delete seq;
Reversing
//Reversing creates a new sequence and the older sequence is not modified.
//So assign it to the var or hold it in a new var
seq = reverse seq;
Comparing
Sequences can be compared using == operator. The equality checks for both size and the values.
var seq10 = ["a", "b"];
var seq11 = ["a", "b"];
var seq12 = ["c","d"];
//Will print true
println(seq10 == seq11);
//Will print false
println(seq11 == seq12);
Extracting Subsequences from Sequence
Extracting based on logic expression
def seq = ["JavaFX", "Silverlight", "Flash"];
//Build a sequence removing "Silverlight"
def seq1 = seq[x|x != "Silverlight"];
//Will retain "Silverlight" and "Flash"
def seq2 = seq1..2;
//Will retain only JavaFX
def seq3 = seq[0..<1];
//Will retain "Silverlight" and "Flash"
def seq4 = seq[1..];
sequence can be build using steps over a range
//Sequence of 1,2,3,4,5,6,7,8,9,10
var nums = [1..10];
//Sequence of 1,5,9
var nums1 = [1..10 step 4];
//Sequence of 10,6,2. Note that the range is from 10 to 1
No comments:
Post a Comment