0% found this document useful (0 votes)
48 views67 pages

3 Analysis-Streams

This document discusses COSC 222 Data Structures taught by Yves Lucet. It covers topics like generics, complexity analysis, streams, and data structures like hash tables, skip lists, heaps, and trees.

Uploaded by

Arhaan Khaku
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
48 views67 pages

3 Analysis-Streams

This document discusses COSC 222 Data Structures taught by Yves Lucet. It covers topics like generics, complexity analysis, streams, and data structures like hash tables, skip lists, heaps, and trees.

Uploaded by

Arhaan Khaku
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 67

COSC 222 Data Structures

Yves Lucet

CC BY-SA 3.0
https://en.wikipedia.org/wiki/Skip_list#/media/File:Skip_list_add_element-en.gif

"Hash table 3 1 1 0 1 0 0 SP" by Jorge Stolfi - Own work. Licensed under CC BY-SA 3.0 via Commons - 1
https://commons.wikimedia.org/wiki/File:Hash_table_3_1_1_0_1_0_0_SP.svg#/media/File:Hash_table_3_1_1_0_1_0_0_SP.svg
COSC 222
Generics
Complexity
Streams
Wk Class Date Activity Reading/Prep given Peer
1 1 Sep 06 Syllabus, TBL, Java review
2 Sep 08 Git, testing Java, Generics, Testing
2 3 Sep 13 RAT1: generics; unit testing Complexity
4 Sep 15 Lect: Complexity, streams Lists
3 5 Sep 20 Build & Critic (training) iMAT1
6 Sep 22 tMAT1 Recursion
4 7 Sep 27 RAT2 Stack, Queue P eer 1
8 Sep 29 Build & Critic Iterators
5 9 Oct 04 mini-lecture+exercises iMAT2
10 Oct 06 tMAT2 BST, PQ, heap
6 11 Oct 11 RAT3 Hash, skip list P eer 2
12 Oct 13 Hash table, Skiplist, bottom-up
14.6heap
Shortest
construction
path
7 13 Oct 18 Dijsktra+adaptable PQ Union-find
14 Oct 20 Union-find/Disjoint sets iMAT3
8 15 Oct 25 tMAT3 Search Trees AVL/RB
16 Oct 27 Lecture BST, AVL, (2,4), RB B-Trees P eer 3
9 17 Nov 01 B-trees iMAT4
18 Nov 03 tMAT4
10 19 Nov 08 Midterm review
20 Nov 10 Midterm
11 Nov 15 Reading week
Nov 17 Reading week Text processing
12 21 Nov 22 Pattern matching KMP, BM, Trie
22 Nov 24 RAT4 Huffman coding
13 23 Nov 29 Huffman coding iMAT5
24 Dec 01 tMAT5
3
14 25 Dec 06 Review/Course Evaluation P eer 4
RAT appeal/clarifications
iRAT avg: 59% (2022: 58%; 2018: 52%)
 Be aware of the time! 23 ran out of time

tRAT avg: 86% (2022: 88%; 2018: 86%)

Appeals:
 All appeals were rejected (same in 2022)

4
Q11

Coverage testing aims to measure how well your


tests cover different parts of your code, such as
statements, branches, or paths.
T2, 7, 8, 14,18, 19, 23,26, 28, 33 appeal denied
Q6

D is correct answer (type erasure)


T1, T16 and T27 appeals denied
Q8

Compile-time error because of type erasure


T11, 22 appeal denied
An important difference between arrays and generics is how they
enforce type checking. Specifically, arrays store and check type
information at runtime. Generics, however, check for type errors at
compile-time and don’t have type information at runtime.

public <T> T[] getArray(int size) {


T[] genericArray = new T[size]; // suppose this is allowed

return genericArray;
}
becomes at runtime
public Object[] getArray(int size) {
Object[] genericArray = new Object[size];
return genericArray;
}
then
String[] myArray = getArray(5);

gives a compile time error:


8
Type mismatch: cannot convert from Object[] to String[]
Careful
Works java.lang.ArrayStoreException
Integer i = 0; Integer[] I = new Integer[3];
Number n; Number[] N = I;
n = i; N[0] = 4.5;
n = 4.5;

Take away:
• Play it safe: avoid arrays and use compiler to detect errors
• Use ArrayList with generics
• In pseudo-code: differentiate between array vs. list
• In Java: List<T> is an interface
Generics
Last(?) clarification

10
Survey: Generics

Analysis of Algorithms
11
Beware
Integer i = 1;
Number n = i;
n = 4.5;
System.out.println(n);

A. Type mismatch: cannot convert from Float


to Integer
B. Compiles but runtime error
C. Runs fine
D. None of the above

12
Beware
Integer[] I = new Integer[3];
Number[] N = I;
N[0] = 4.5;
System.out.println(Arrays.toString(N));

A. Type mismatch: cannot convert from Integer[]


to Number[]
B. Compiles but runtime error
C. Runs fine
D. None of the above

13
Beware
List<Integer> li = new ArrayList<Integer>();
List<Number> ln = li;
ln.add(3.1415);

A. Type mismatch: cannot convert from List<Integer>


to List<Number>
B. Compiles but runtime error
C. Runs fine
D. None of the above

14
Do not work around generics!
List<?>[] lsa = new List<?>[10];
Object[] oa = lsa;//OK because List<String> is a subtype of Object
List<Integer> li = new ArrayList<Integer>();
li.add(Integer.valueOf(3));
oa[0] = li;
String s = lsa[0].get(0).toString();
System.out.println(s);

The code works, but


1. is complicated, and very hard to read
2. is not taking advantage of generics
Keep it simple!

15
Questions?

This Photo by Unknown Author is licensed under CC BY 16


Analysis of Algorithms

Input Algorithm Output

An algorithm is a step-by-step procedure for


solving a problem in a finite amount of time.
Big-Oh Rules

If is f(n) a polynomial of degree d, then f(n) is


O(nd), i.e.,
1. Drop lower-order terms
2. Drop constant factors
Use the smallest possible class of functions
 Say “2n is O(n)” instead of “2n is O(n2)”
Use the simplest expression of the class
 Say “3n + 5 is O(n)” instead of “3n + 5 is O(3n)”

18
500

450

400

350

300

n
n log n
250 n^2
n^3
exp(n)

200

150

100

50

0 Analysis of Algorithms
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 19
Tips
log < polynomial < exponential
Polynomials are ordered by increasing
powers
Most common complexities:
,,,,,

20
Survey

Analysis of Algorithms
21
GameEntry[] A = new GameEntry[10];
for (int i=0; i < 10; i++){A[i] = new GameEntry();}
A[4].score = 200;
B = A.clone();
B[4].score = 550;
System.out.println(A[4].score);
The code compiles and displays
A. 200
B. 550
C. null
D. a runtime exception is thrown
E. I don’t know
22
The notation n=O(n2) means
A. n is growing faster than n2
B. n is growing slower than n2
C. n is an object to be initialized as n2
D. n is an object to be assigned from n2
E. n is a number and is assigned the
value O(n2) where O is a function

23
Which answer has the tightest
bound?

A. n = O(n2+2)
B. n2+2n -1 = O(n2)
C. O(n2) = n3+2n -1
D. n2+2n -1 = O(n3)
E. n2+2n -1 = O(2n)

24
The slowest growing function is:
A.
n
B.
n log(n)
n
C.
2
log n
D. n
E.

25
Sorting an array takes…

A. Quadratic time
B. Linear time
C. Logarithmic time
D. Exponential time
E. Cubic time

26
Computing the sum of all
elements in an array takes…

A. Quadratic time
B. Linear time
C. Logarithmic time
D. Exponential time
E. Cubic time

27
Questions?

This Photo by Unknown Author is licensed under CC BY 28


Streams in Java 8

29
Javascript jQuery
$(document).ready(function(){
$("div").find("span").css({"color": "red", "border": "2px solid red"});
});

30
Stream

Lambda expression
31
int sum = 0;
for (int x : numbers) {
sum += x;
}

int sum = numbers.stream().reduce(0, (x,y) -> x+y);

32
Lambda expressions
Anonymous inner classes
short form replacement for anonymous
inner class
 neat and concise syntax
 easy to use and make program more
readable

33
Anonymous Inner Classes
provide a way to implement classes that
may occur only once in an application
JButton testButton = new JButton("Test Button");
testButton.addActionListener(new ActionListener(){
@Override public void actionPerformed(ActionEvent ae){
System.out.println("Click Detected by Anon Class");
}
});

34
Functional Interfaces
an interface with only one method

package java.awt.event;
import java.util.EventListener;

public interface ActionListener extends EventListener {

public void actionPerformed(ActionEvent e);

35
Functional Interfaces
an interface with only one method
 Exception: other methods must be
methods defined in java.lang.Object
public interface SayHello {
String say(String message);
String toString();
}

36
public class FirstExample {

interface SayHello {
String say(String message);
}

public static void main(String[] args) {

//Saying hello through anonymous class


SayHello helloAnonymous = new SayHello() {

@Override
public String say(String message) {
return "Hello " + message;
}
};
System.out.println(helloAnonymous.say("Annonymous Class"));

//Saying hello through lambda expression


SayHello helloLambdaExpr = (String message) -> "Hello " + message;
System.out.println(helloLambdaExpr.say("Lambda Expression"));
}
}

http://javaattop.blogspot.in/2013/09/lambda-expressions-in-java.html 37
RULE 1:
If the abstract method of functional interface is a zero argument
method, then in the left hand side of the arrow(->) we must use an
empty parentheses.

public class SecondExample {

interface StaticMessage {
String say();
}

public static void main(String[] args) {

//Observe the empty parentheses


StaticMessage msg = () -> "A Fixed Message";
System.out.println(msg.say());
}
}

http://javaattop.blogspot.in/2013/09/lambda-expressions-in-java.html 38
RULE 2:
If the abstract method of functional interface is a one-argument
method, then the parentheses is not mandatory.

public class ThirdExample {

interface SayHello {
String say(String message);
}

public static void main(String[] args) {

SayHello sh = message -> "Hello " + message;


System.out.println(sh.say("Lambda Expression"));
}
}

http://javaattop.blogspot.in/2013/09/lambda-expressions-in-java.html 39
RULE 4:
Mentioning type of the formal parameters are not mandatory. In
case you have not mentioned the type of formal parameters, then its
type will be determined by the Java compiler from the corresponding
Target Type.
SayHello sh =
(msg, name, sex) -> {
if(sex == Sex.MALE) {
return "Hello Mr. " + name + ", " + msg;
} else {
return "Hello Ms. " + name + ", " + msg;
}
};

http://javaattop.blogspot.in/2013/09/lambda-expressions-in-java.html 40
RULE:
The body of a lambda expression can either be a single
expression or one or more statements.
public class FifthExample {
interface SayHello {
String hello(String name);
}

public static void main(String...args) {

//Saying hello through lambda expression using single expression


SayHello sh1 = msg -> "Hello " + msg;
System.out.println(sh1.hello("Lambda Expression With Expression"));

//Saying hello through lambda expression using statement


SayHello sh2 = msg -> { return "Hello " + msg; };
System.out.println(sh2.hello("Lambda Expression With Statement"));

//With multiple statements


SayHello sh3 = msg -> { String hello = "Hello " + msg;
return hello;
};
System.out.println(sh3.hello("Lambda Expression With Multiple Statement"));
}
} 41
http://javaattop.blogspot.in/2013/09/lambda-expressions-in-java.html
Example: Comparators

Comparator<Person> comparator = (p1, p2) -> p1.firstName.compareTo(p2.firstName);

Person p1 = new Person("John", "Doe");


Person p2 = new Person("Alice", "Wonderland");

comparator.compare(p1, p2); // > 0


comparator.reversed().compare(p1, p2); // < 0

42
http://winterbe.com/posts/2014/03/16/java-8-tutorial/
http://javaattop.blogspot.ca/2013/09/lambda-expressions-in-java.html 43
Even though this
interface contains
3 methods it can
be implemented by
a lambda
expression,
because only one
of the methods is
44
unimplemented.
Streams
Not I/O streams

45
Streams
represents sequence of elements
supports operations on these elements
List<String> myList = Arrays.asList("a1", "a2", "b1", "c2", "c1");

myList
.stream()
.filter(s -> s.startsWith("c"))
.map(String::toUpperCase)
.sorted()
.forEach(System.out::println);

// C1
// C2

46
Streams
operations are either
intermediate: return a stream
 chained in operation pipeline
terminal: void or return non-stream
List<String> myList = Arrays.asList("a1", "a2", "b1", "c2", "c1");

myList
.stream()
.filter(s -> s.startsWith("c"))
.map(String::toUpperCase)
.sorted()
.forEach(System.out::println);

47
http://winterbe.com/posts/2014/07/31/java8-stream-tutorial-examples/
Streams
most stream operations accept lambda
expression as parameter that needs to be
non-interfering
 does not modify underlying data source
stateless
 execution is deterministic: does not depend
on variables/states from the outer scope
which might change during execution

48
http://winterbe.com/posts/2014/07/31/java8-stream-tutorial-examples/
Streams
stream()
 Arrays.asList("a1", "a2", "a3").stream().findFirst().
 Stream.of("a1", "a2", "a3").findFirst().
parallelStream()
 operate on multiple threads

49
http://winterbe.com/posts/2014/07/31/java8-stream-tutorial-examples/
Sequential Streams
IntStream, LongStream, DoubleStream
 IntStream.range(1,
4) .forEach(System.out::println);
 use specialized lambda expression
 IntFunction instead of Function
 IntPredicate instead of Predicate
 support
 sum()
 average()

50
http://winterbe.com/posts/2014/07/31/java8-stream-tutorial-examples/
Sequential Streams
transform
 Stream.of("a1", "a2", "a3")
.map(s -> s.substring(1))
.mapToInt(Integer::parseInt)
.max()
.ifPresent(System.out::println); // 3
 IntStream.range(1, 4)
.mapToObj(i -> "a" + i)
.forEach(System.out::println);// a1, a2, a3
51
http://winterbe.com/posts/2014/07/31/java8-stream-tutorial-examples/
Comparator c = (Computer c1, Computer c2) ->
c1.getAge().compareTo(c2.getAge());

Comparator c = (c1, c2) ->


c1.getAge().compareTo(c2.getAge());

Comparator c =
Comparator.comparing(Computer::getAge);

https://www.baeldung.com/java-8-double-colon-operator
52
Creating a new instance
@FunctionalInterface
public interface InterfaceComputer {
Computer create();
}
InterfaceComputer c = Computer::new;
Computer computer = c.create();

Do not go overboard!
Use when it makes the code easier to read
https://www.baeldung.com/java-8-double-colon-operator
53
Processing order
laziness
 Stream.of("d2", "a2", "b1", "b3", "c")
.filter(s -> {
System.out.println("filter: " + s);
return true;
});//nothing printed (no terminal operation)
 Stream.of("d2", "a2", "b1", "b3", "c")
.filter(s -> {
System.out.println("filter: " + s);
return true;
})
.forEach(s -> System.out.println("forEach: " + s));//print as expected

54
http://winterbe.com/posts/2014/07/31/java8-stream-tutorial-examples/
filter: d2
Processing order forEach:
filter:
d2
a2
forEach: a2
filter: b1
laziness forEach:
filter:
b1
b3
 Stream.of("d2", "a2", "b1", "b3", "c") forEach: b3
.filter(s -> { filter: c
System.out.println("filter: " + s); forEach: c
return true;
})
.forEach(s -> System.out.println("forEach: " + s));

operations executed vertically

55
http://winterbe.com/posts/2014/07/31/java8-stream-tutorial-examples/
map: d2
Processing order anyMatch: D2
map: a2
anyMatch: A2

map called only twice


 Stream.of("d2", "a2", "b1", "b3", "c")
.map(s -> {
System.out.println("map: " + s);
return s.toUpperCase();
})
.anyMatch(s -> {
System.out.println("anyMatch: " + s);
return s.startsWith("A");
});

order matters when you wish to minimize number of operations


 filter before sort

56
http://winterbe.com/posts/2014/07/31/java8-stream-tutorial-examples/
Last points
streams cannot be reused after terminal
operation
 Stream<String> stream =
Stream.of("d2", "a2", "b1", "b3", "c")
.filter(s -> s.startsWith("a"));

stream.anyMatch(s -> true); // ok


stream.noneMatch(s -> true); // exception

57
http://winterbe.com/posts/2014/07/31/java8-stream-tutorial-examples/
Reference
Java 8 Streams: plenty of
tutorial/reference material online, for
example
 https://winterbe.com/posts/2014/07/31/jav
a8-stream-tutorial-examples/
 https://stackify.com/streams-guide-java-8/

63
Survey

Analysis of Algorithms
64
import java.util.*;
import java.util.stream.IntStream;
public class HelloWorld {
public static void main(String []args) {
System.out.println(IntStream.range(1, 4).sum());
}
}

The code
A. displays 6
B. Throws a runtime exception
C. Does not compile
D. Displays 10
E. I don’t know 65
import java.util.*;
public class HelloWorld {
public static void main(String []args) {
Arrays.stream(new int[] {1, 2, 3})
.map(n -> 2 * n + 1)
.average()
.ifPresent(System.out::println);
}
}
The code
A. displays 6
B. Throws a runtime exception
C. Does not compile
D. Displays 5
E. I don’t know 66
import java.util.*;
import java.util.stream.IntStream;
public class HelloWorld {
public static void main(String []args) {
IntStream.range(1, 4)
.mapToObj(i -> "a" + i)
.forEach(System.out::print);
}
}

The code
A. displays 123
B. Throws a runtime exception
C. Does not compile
D. Displays a1a2a3
E. I don’t know 67
import java.util.*;import java.util.stream.*;
public class Person {
String name; int age;
Person(String name, int age) {this.name = name; this.age = age;}
@Override public String toString() {return name;}
public static void main(String []args) {
List<Person> persons = Arrays.asList(
new Person("Max", 18), new Person("Peter", 22),
new Person("Pamela", 23), new Person("David", 12));
persons.stream()
.reduce((p1, p2) -> p1.age > p2.age ? p1 : p2)
.ifPresent(System.out::println);
}
}
The code compiles and print
A. Max
B. Peter
C. David
D. Pamela
E. I don’t know 68
Summary
Complexity. You should be able to
 sort functions by asymptotic worst-case complexity
 compute the space and time complexity of a simple
code
Stream. You should be able to
 understand code written using streams
 write simple code using streams
 explain the reason to use streams:
 code readability
 parallelism

69
Questions?

This Photo by Unknown Author is licensed under CC BY 70


Readings for next time
See Readings page on Canvas

71
THE END

72

You might also like