Collectors. Raoul-Gabriel Urma Richard Warburton James Gough
|
|
- Dennis O’Neal’
- 6 years ago
- Views:
Transcription
1 Collectors Raoul-Gabriel Urma Richard Warburton James Gough
2 Outline of module 1. Grouping and partitioning 2. Collection operations 3. Arithmetic and reducing collectors 4. Advanced queries
3 Grouping and partitioning
4 Collectors Most terminal operations that you ve seen so far were returning a single value E.g. boolean, int collect(tolist()) was returning a List collect takes a recipe to accumulate the elements of a stream into a container This recipe is a Collector object and is the parameter passed to the method collect
5 Collectors are fun and expressive (1) Map<Currency, List<Transaction>> transactionsbycurrencies = new HashMap<>(); for (Transaction transaction : transactions) { Currency currency = transaction.getcurrency(); List<Transaction> transactionsforcurrency = transactionsbycurrencies.get(currency); } if (transactionsforcurrency == null) { transactionsforcurrency = new ArrayList<>(); transactionsbycurrencies.put(currency, transactionsforcurrency); } transactionsforcurrency.add(transaction);
6 Collectors are fun and expressive (2) import static java.util.stream.collectors.groupingby; Map<Currency, List<Transaction>> transactionsbycurrencies = transactions.stream().collect(groupingby(transaction::getcurrency)); Reads like problem statement can be parallelised by using the method parallelstream
7 Grouping "GROUP BY" operation inspired from SQL Groups Stream elements according to a classification function, and returns the results in a Map. Map<Dish.Type, List<Dish>> dishesbytype = menu.stream().collect(groupingby(dish::gettype));
8 Partitioning Special case of grouping, which takes a partitioning function A partitioning function is a Predicate (a function that returns a boolean) Map<Boolean, List<Dish>> vegetariandishesbytype = menu.stream().collect(partitioningby(dish::isvegetarian)); { } false=[pork, beef, chicken, prawns, salmon], true=[french fries, rice, season fruit, pizza]
9 Exercise 1. Partition the list of dishes Dishes with calories > Group the list of dishes by CaloricLevel public enum CaloricLevel { DIET, NORMAL, FAT } 0 < DIET <= 400 calories 400 < NORMAL <= 700 FAT > 700 com.java_8_training.problems.collectors.partitioningandgroupingtest
10 Collection Operations
11 Collecting to lists and sets You ve seen tolist() already: List<Dish> dish = menu.stream().filter(dish::isvegetarian).collect(tolist()); You can also use toset(): Set<Dish> dish = menu.stream().filter(dish::isvegetarian).collect(toset());
12 Flexible collection You can use tocollection(supplier) for more flexibility Deque<Dish> dish = menu.stream().filter(dish::isvegetarian).collect(tocollection(arraydeque::new));
13 Exercise How would you remove duplicates from a list of numbers using Streams operations using a collector How would you transform a Stream into a TreeSet? com.java_8_training.problems.collectors. CollectTest
14 Arithmetic and reducing Collectors
15 Maximum and minimum Comparator<Dish> dishcaloriescomparator = Comparator.comparingInt(Dish::getCalories); Optional<Dish> mostcalorificdish = menu.stream().collect(maxby(dishcaloriescomparator)); Optional<Dish> leastcalorificdish = menu.stream().collect(minby(dishcaloriescomparator));
16 Counting long howmanydishes = menu.stream().collect(counting()); long howmanydishes = menu.stream().count(); The counting Collector can be useful especially when used in combination with other Collectors, as we ll demonstrate later.
17 Sum and Average Sum the values of using an extraction function which returns a number. (summingint, summinglong, summingdouble) int totalcalories = menustream.collect(summingint(dish::getcalories)); Calculate the average value using an extraction function which returns a number. (averagingint, averaginglong, averagingdouble) int avgcalories = menustream.collect(averagingint(dish::getcalories));
18 Summary statistics Returns summary statistics in a single operation using an extraction function that returns a number summarizingint, summarizinglong, summarizingdouble IntSummaryStatistics menustatistics = menu.stream().collect(summarizingint(dish::getcalories)); IntSummaryStatistics{count=9, sum=4300, min=120, average= , max=800}
19 Joining Concatenate the Strings resulting from the invocation of the tostring method on each item of the Stream. Internally makes use of StringBuilder String shortmenu = menu.stream().map(dish::getname).collect(joining(", ")); pork, beef, chicken, french fries, rice, season fruit, pizza, prawns, salmon
20 Reducing - three args Reduce the stream to a single value. It takes three parameters: 1. Identity: initial value and/or the default result if there are no elements in the stream. 2. Transforming function: The reducing operation applies this function to all stream elements. 3. Aggregating function: the aggregating function is used to iteratively combine the mapped values. Useful for multi-level reductions (e.g. together with groupingby - more later) int totalcalories = menu.stream().collect(reducing(0, Dish::getCalories, Integer::sum));
21 Reducing - three args int totalcalories = menu.stream().collect(reducing(0, Dish::getCalories, Integer::sum));
22 Reducing (3) - one arg Comparator<Dish> dishcaloriescomparator = Comparator.comparingInt(Dish::getCalories); BinaryOperator<Dish> maxbycalories = BinaryOperator.maxBy(dishCaloriesComparator); Optional<Dish> mostcalorificdish = menu.stream().collect(reducing(maxbycalories));
23 Reducing (4) - two args int totalcalories = menu.stream().map(dish::getcalories).collect(reducing(0, Integer::sum));
24 Quiz Which of the following statements are correct using the reducing Collector? String shortmenu = menu.stream().map(dish::getname).collect( reducing( (s1, s2) -> s1 + s2) ) ).get(); String shortmenu = menu.stream().collect( reducing( (d1, d2) -> d1.getname() + d2.getname() ) ).get(); String shortmenu = menu.stream().collect( reducing( "", Dish::getName, (s1, s2) -> s1 + s2) ) );
25 Exercise 1. Find the least caloric dish that is of type MEAT 2. Return statistics (average, sum, min, max) of the calories of vegetarian dishes com.java_8_training.problems.collectors. ArithmeticAndReducingCollectorsTest
26 Advanced queries
27 Composing collectors (1) The collectors groupingby and partitioningby accept other collectors as argument to create more complex queries. Map<Dish.Type, Long> typescount = menu.stream().collect( groupingby(dish::gettype, counting())); produces: {MEAT=3, FISH=2, OTHER=4}
28 Composing collectors (2) Map<Dish.Type, Integer> totalcaloriesbytype = menu.stream().collect( groupingby(dish::gettype, summingint(dish::getcalories)) );
29 Composing collectors (3) Map<Dish.Type, Optional<Dish>> mostcaloricbytype = menu.stream().collect(groupingby(dish::gettype, maxby(comparingint(dish::getcalories))));
30 Exercise Generate a Map of occurrences of characters in a sentence E.g. cool -> { c :1, o :2, l :1} Can you extend it to work with a List of sentences? com.java_8_training.problems.collectors. OccurrencesTest
31 collectingandthen (1) Wraps another Collector and apply a transformation function to its result. int howmanydishes = menustream.collect(collectingandthen(tolist(), List::size));
32 collectingandthen(2) Map<Dish.Type, Optional<Dish>> mostcaloricbytype = menu.stream().collect(groupingby(dish::gettype, maxby(comparingint(dish::getcalories)))); VS Map<Dish.Type, Dish> mostcaloricbytype = menu.stream().collect( groupingby(dish::gettype, collectingandthen( maxby(comparingint(dish::getcalories)), Optional::get)));
33 Multi-level groupings (1)
34 Multi-level groupings (2) enum CaloricLevel { DIET, NORMAL, FAT }; CaloricLevel getcaloriclevel() { if (getcalories() <= 400) return CaloricLevel.DIET; else if (getcalories() <= 700) return CaloricLevel.NORMAL; else return CaloricLevel.FAT; }
35 Multi-level groupings (3) Map<Dish.Type, Map<CaloricLevel, List<Dish>>> dishedbytypecaloriclevel = ); menu.stream().collect( groupingby(dish::gettype, ) groupingby(dish::getcaloriclevel)
36 Quiz What are the following doing? 1. menu.stream().collect(partitioningby(dish:: isvegetarian, partitioningby(d -> d.getcalories() > 500))); 2. menu.stream().collect(partitioningby(dish:: isvegetarian, partitioningby(dish::gettype))); 3. menu.stream().collect(partitioningby(dish:: isvegetarian, counting()));
37 Optional Exercise: Financial data processing
38 Exercise Continuation of trader and transactions unit tests Look at test: com.java_8_training.problems.collectors. TransactionsAndTradesPart2Test
39 Mutable reduction (Optional)
40 Collect vs. Reduce Reduce is an immutable reduction combine values and produce a new value Collect is a mutable reduction accumulates elements into a container Collectors let you abstract and re-use reduction strategies
41 Reduce - what s the problem? Stream<Integer> stream = Arrays.asList(1, 2, 3, 4, 5, 6). stream(); List<Integer> numbers = stream.reduce( new ArrayList<Integer>(), (List<Integer> l, Integer e) -> { l.add(e); return l; }, (List<Integer> l1, List<Integer> l2) -> { l1.addall(l2); return l1; });
42 Collect Stream<Integer> stream = Arrays.asList(1, 2, 3, 4, 5, 6). stream(); List<Integer> numbers = stream.collect(arraylist::new, List::add, List::addAll);
43 Implementing a Collector public interface Collector<T, A, R> { Supplier<A> supplier(); BiConsumer<A, T> accumulator(); Function<A, R> finisher(); BinaryOperator<A> combiner(); Set<Characteristics> characteristics(); }
44
45 ToListCollector public class ToListCollector<T> implements Collector<T, List<T>, List<T>> { } public Supplier<List<T>> supplier() { } return () -> new ArrayList<T>(); public BiConsumer<List<T>, T> accumulator() { } return (list, item) -> list.add(item); public Function<List<T>, List<T>> finisher() { } return Function.identity(); public BinaryOperator<List<T>> combiner() { } return (list1, list2) -> { }; list1.addall(list2); return list1;
46 public Supplier<List<T>> supplier() { } return () -> new ArrayList<T>();
47 public BiConsumer<List<T>, T> accumulator() { return (list, item) -> list.add(item); }
48 public Function<List<T>, List<T>> finisher() { } return Function.identity();
49 public BinaryOperator<List<T>> combiner() { return (list1, list2) -> { list1.addall(list2); return list1; }; }
50 Use your collector Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5, 6) List<Integer> numbers = stream.collect(new ToListCollector<>());
Multicore Programming
Multicore Programming Java Streams Louis-Claude Canon louis-claude.canon@univ-fcomte.fr Bureau 414C Master 1 informatique Semestre 8 Louis-Claude Canon MCP Java Streams 1 / 124 Motivations Express simple
More informationLambdas, streams, and functional-style programming IN ACTION. Raoul-Gabriel Urma Mario Fusco Alan Mycroft S AMPLE CHAPTER MANNING
Lambdas, streams, and functional-style programming IN ACTION Raoul-Gabriel Urma Mario Fusco Alan Mycroft S AMPLE CHAPTER MANNING Java 8 in Action by Raoul-Gabriel Urma Mario Fusco Alan Mycroft Chapter
More informationLesson 3-4: Using Collectors
Lesson 3-4: Using Collectors Collector Basics A Collector performs a mutable reduction on a stream Accumulates input elements into a mutable result container Results container can be a List, Map, String,
More informationJava8: Stream Style. Sergey
Java8: Stream Style Sergey Kuksenko sergey.kuksenko@oracle.com, @kuksenk0 The following is intended to outline our general product direction. It is intended for information purposes only, and may not be
More informationCMSC 202. Containers
CMSC 202 Containers Container Definition A container is a data structure whose purpose is to hold objects. Most languages support several ways to hold objects. Arrays are compiler-supported containers.
More informationCOMP6700/2140 Stream Pipelines
COMP6700/2140 Stream Pipelines Alexei B Khorev Research School of Computer Science, ANU April 2017 Alexei B Khorev (RSCS, ANU) COMP6700/2140 Stream Pipelines April 2017 1 / 28 Topics 1 Idioms of Stream
More informationJava SE 8 Programming
Java SE 8 Programming Training Calendar Date Training Time Location 16 September 2019 5 Days Bilginç IT Academy 28 October 2019 5 Days Bilginç IT Academy Training Details Training Time : 5 Days Capacity
More informationJava SE 8 Programming
Oracle University Contact Us: +52 1 55 8525 3225 Java SE 8 Programming Duration: 5 Days What you will learn This Java SE 8 Programming training covers the core language features and Application Programming
More informationJava Technologies. Lecture V. Valdas Rapševičius
Preparation of the material was supported by the project Increasing Internationality in Study Programs of the Department of Computer Science II, project number VP1 2.2 ŠMM-07-K-02-070, funded by The European
More informationStreams in Java 8. Start programming in a more functional style
Streams in Java 8 Start programming in a more functional style Background Who am I? Tobias Coetzee I m a Technical Lead at BBD I present the Java Expert Level Certifications at BBD (EJB, JPA, etc.) I m
More informationCMSC 202H. Containers and Iterators
CMSC 202H Containers and Iterators Container Definition A container is a data structure whose purpose is to hold objects. Most languages support several ways to hold objects Arrays are compiler-supported
More informationJava SE 8 Programming
Oracle University Contact Us: Local: 1800 103 4775 Intl: +91 80 67863102 Java SE 8 Programming Duration: 5 Days What you will learn This Java SE 8 Programming training covers the core language features
More informationAdvanced Java Programming
Advanced Java Programming Programming Technologies 2015/2016 spring Kollár, Lajos Kocsis, Gergely (English version) Advanced Java Programming Java 5 Generics (Enums) Java 7 Strings in switch try-with-resources
More informationArray Based Lists. Collections
Array Based Lists Reading: RS Chapter 15 1 Collections Data structures stores elements in a manner that makes it easy for a client to work with the elements Specific collections are specialized for particular
More informationGenerics: Past, Present
Generics: Past, Present and Future @richardwarburto @raouluk binarysearch(list
More informationFunctional Programming in Java Part 2. CSE 219 Department of Computer Science, Stony Brook University
Functional Programming in Java Part 2 CSE 219, Stony Brook University Functions as Objects The interface java.util.function.function To store a function (i.e., take a single argument and returns a
More informationInterview Questions I received in 2017 and 2018
Interview Questions I received in 2017 and 2018 Table of Contents INTERVIEW QUESTIONS I RECEIVED IN 2017 AND 2018... 1 1 OOPS... 3 1. What is the difference between Abstract and Interface in Java8?...
More informationpublic static boolean isoutside(int min, int max, int value)
See the 2 APIs attached at the end of this worksheet. 1. Methods: Javadoc Complete the Javadoc comments for the following two methods from the API: (a) / @param @param @param @return @pre. / public static
More informationORACLE TRAINING CURRICULUM. Relational Databases and Relational Database Management Systems
ORACLE TRAINING CURRICULUM Relational Database Fundamentals Overview of Relational Database Concepts Relational Databases and Relational Database Management Systems Normalization Oracle Introduction to
More informationParsing JSON, Using Libraries, Java Collections, Generics. Slides adapted from Craig Zilles
Parsing JSON, Using Libraries, Java Collections, Generics Slides adapted from Craig Zilles 1 CamelCaser Difficulty How difficult was the first assignment? A. Easy B. Moderate C. Challenging D. Unreasonable
More informationJava 8 Parallel Stream Internals (Part 2)
Java 8 Parallel Stream Internals (Part 2) Douglas C. Schmidt d.schmidt@vanderbilt.edu www.dre.vanderbilt.edu/~schmidt Professor of Computer Science Institute for Software Integrated Systems Vanderbilt
More informationInterfaces and Collections
Interfaces and Collections COMPSCI 2S03 Mikhail Andrenkov Department of Computing and Software McMaster University Week 9: November 14-18 Mikhail Andrenkov Interfaces and Collections 1 / 25 Outline 1 Interfaces
More informationSolutions to Quiz 1 (March 14, 2016)
MIT 6.005: Software Construction Max Goldman revised Wednesday 16 th March, 2016, 14:08 Solutions to Quiz 1 (March 14, 2016) Problem 1 (Multiple Choice) (20 points). (a) Which of the following must be
More informationCS 200 Objects and ArrayList Jim Williams, PhD
CS 200 Objects and ArrayList Jim Williams, PhD This Week 1. Academic Integrity 2. BP1: Milestone 2 due this week 3. Team Lab: Multi-Dimensional Arrays a. Bring paper and pencil to draw diagrams. b. Code
More informationΠΙΝΑΚΑΣ ΠΛΑΝΟΥ ΕΚΠΑΙΔΕΥΣΗΣ
ΠΑΡΑΡΤΗΜΑ «Β» ΠΙΝΑΚΑΣ ΠΛΑΝΟΥ ΕΚΠΑΙΔΕΥΣΗΣ Α/Α ΠΕΡΙΓΡΑΦΗ ΕΚΠΑΙΔΕΥΣΗΣ ΘΕΜΑΤΙΚΕΣ ΕΝΟΤΗΤΕΣ 1. Java SE8 Fundamentals What Is a Java Program? Introduction to Computer Programs Key Features of the Java Language
More informationQuiz 1 (March 14, 2016)
MIT 6.005: Software Construction Max Goldman revised Sunday 13 th March, 2016, 15:30 Quiz 1 (March 14, 2016) Your name: Your Athena username: You have 50 minutes to complete this quiz. It contains 12 pages
More informationComputer Science II (20082) Week 1: Review and Inheritance
Computer Science II 4003-232-08 (20082) Week 1: Review and Inheritance Richard Zanibbi Rochester Institute of Technology Review of CS-I Syntax and Semantics of Formal (e.g. Programming) Languages Syntax
More informationWeek 16: More on Collections and Immutability
Week 16: More on Collections and Immutability Jack Hargreaves jxh576@cs.bham.ac.uk Febuary 9, 2012 1 Collections API Last week we looked at Collection, List, Set and Map the basic data type interfaces
More informationAdvanced Programming Methods. Lecture 4 - Functional Programming in Java
Advanced Programming Methods Lecture 4 - Functional Programming in Java Important Announcement: At Seminar 6 (7-13 November 2017) you will have a closed-book test (based on your laboratory work). Overview
More informationComputer Programming
Computer Programming Dr. Deepak B Phatak Dr. Supratik Chakraborty Department of Computer Science and Engineering Session: while and do while statements in C++ Dr. Deepak B. Phatak & Dr. Supratik Chakraborty,
More informationVisual C# 2012 How to Program by Pe ars on Ed uc ati on, Inc. All Ri ght s Re ser ve d.
Visual C# 2012 How to Program 1 99 2-20 14 by Pe ars on Ed uc ati on, Inc. All Ri ght s Re ser ve d. 1992-2014 by Pearson Education, Inc. All 1992-2014 by Pearson Education, Inc. All Although commonly
More informationAdvanced Programming Generics Collections
Advanced Programming Generics Collections The Context Create a data structure that stores elements: a stack, a linked list, a vector a graph, a tree, etc. What data type to use for representing the elements
More informationDOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS
Chapter 1 : Chapter-wise Java Multiple Choice Questions and Answers Interview MCQs Java Programming questions and answers with explanation for interview, competitive examination and entrance test. Fully
More informationPieter van den Hombergh Thijs Dorssers Stefan Sobek. June 8, 2017
Pieter van den Hombergh Thijs Dorssers Stefan Sobek Fontys Hogeschool voor Techniek en Logistiek June 8, 2017 /FHTenL June 8, 2017 1/19 Collection Zoo The basic collections, well known in programming s
More informationAdam Blank Lecture 5 Winter 2019 CS 2. Introduction to Programming Methods
Adam Blank Lecture 5 Winter 2019 CS 2 Introduction to Programming Methods CS 2: Introduction to Programming Methods Java Collections Abstract Data Types (ADT) 1 Abstract Data Type An abstract data type
More informationTest 6. moodle.yorku.ca CSE 1020
Test 6 When: Friday March 14, during the lab (14:30 16:00) Where: Lassonde building, labs 1006, 1004, 1002 Material: Chapter 1 8 of the textbook, with a focus on Chapter 8 What: One programming question
More informationThe list abstract data type defined a number of operations that all list-like objects ought to implement:
Chapter 7 Polymorphism Previously, we developed two data structures that implemented the list abstract data type: linked lists and array lists. However, these implementations were unsatisfying along two
More informationHKTA TANG HIN MEMORIAL SECONDARY SCHOOL SECONDARY 3 COMPUTER LITERACY. Name: ( ) Class: Date: Databases and Microsoft Access
Databases and Microsoft Access Introduction to Databases A well-designed database enables huge data storage and efficient data retrieval. Term Database Table Record Field Primary key Index Meaning A organized
More informationCS61B Lecture #24. Today: Java support for generic programming. Readings for today: A Java Reference, Chapter 10.
CS61B Lecture #24 Today: Java support for generic programming Readings for today: A Java Reference, Chapter 10. Readings for Monday: Data Structures, 6.4. Last modified: Fri Oct 19 19:33:03 2012 CS61B:
More informationIndex. object lifetimes, and ownership, use after change by an alias errors, use after drop errors, BTreeMap, 309
A Arithmetic operation floating-point arithmetic, 11 12 integer numbers, 9 11 Arrays, 97 copying, 59 60 creation, 48 elements, 48 empty arrays and vectors, 57 58 executable program, 49 expressions, 48
More informationUSAL1J: Java Collections. S. Rosmorduc
USAL1J: Java Collections S. Rosmorduc 1 A simple collection: ArrayList A list, implemented as an Array ArrayList l= new ArrayList() l.add(x): adds x at the end of the list l.add(i,x):
More informationBuilding Java Programs Chapter 19
Building Java Programs Chapter 19 Functional Programming with Java 8 Copyright (c) Pearson 2016. All rights reserved. What is FP? functional programming: A style of programming that emphasizes the use
More informationEfficient Java (with Stratosphere) Arvid Heise, Large Scale Duplicate Detection
Efficient Java (with Stratosphere) Arvid Heise, Large Scale Duplicate Detection Agenda 2 Bottlenecks Mutable vs. Immutable Caching/Pooling Strings Primitives Final Classloaders Exception Handling Concurrency
More informationCSC 207 (17fa) Practice Final Page 1 of 19. Practice Final
CSC 207 (17fa) Practice Final Page 1 of 19 Practice Final Like the midterms, the final is closed-book, closed technology. The examination period is 180 minutes. The final covers everything that we have
More informationC++ (Non for C Programmer) (BT307) 40 Hours
C++ (Non for C Programmer) (BT307) 40 Hours Overview C++ is undoubtedly one of the most widely used programming language for implementing object-oriented systems. The C++ language is based on the popular
More informationBuilding Java Programs
Building Java Programs Chapter 10 ArrayList reading: 10.1 Welcome to CSE 143! 2 Words exercise Write code to read a file and display its words in reverse order. A solution that uses an array: String[]
More informationCS 10: Problem solving via Object Oriented Programming Winter 2017
CS 10: Problem solving via Object Oriented Programming Winter 2017 Tim Pierson 260 (255) Sudikoff Streams Agenda 1. Streaming data 2. Java streams 2 Streams allow us to process things as they come Stream
More informationTeradata SQL Features Overview Version
Table of Contents Teradata SQL Features Overview Version 14.10.0 Module 0 - Introduction Course Objectives... 0-4 Course Description... 0-6 Course Content... 0-8 Module 1 - Teradata Studio Features Optimize
More informationSoftware 1 with Java. Recitation No. 6 (Collections)
Software 1 with Java Recitation No. 6 (Collections) Java Collections Framework Collection: a group of elements Interface Based Design: Java Collections Framework Interfaces Implementations Algorithms 2
More informationDiscover how to get up and running with the Java Development Environment and with the Eclipse IDE to create Java programs.
Java SE11 Development Java is the most widely-used development language in the world today. It allows programmers to create objects that can interact with other objects to solve a problem. Explore Java
More informationHigher-Order Sequential Operations
Chapter 9 Higher-Order Sequential Operations Many of the operations we wish to perform over lists have common structure. In this chapter, we investigate the most common of these patterns and how we can
More informationSubclass Gist Example: Chess Super Keyword Shadowing Overriding Why? L10 - Polymorphism and Abstract Classes The Four Principles of Object Oriented
Table of Contents L01 - Introduction L02 - Strings Some Examples Reserved Characters Operations Immutability Equality Wrappers and Primitives Boxing/Unboxing Boxing Unboxing Formatting L03 - Input and
More informationSoftware 1 with Java. Java Collections Framework. Collection Interfaces. Online Resources. The Collection Interface
Java Collections Framework Collection: a group of elements Based Design: Software 1 with Java Java Collections Framework s s Algorithms Recitation No. 6 (Collections) 2 Collection s Online Resources Collection
More informationAP CS Unit 7: Interfaces Exercises Assume all code compiles unless otherwise suggested.
AP CS Unit 7: Interfaces Exercises Assume all code compiles unless otherwise suggested. 1. The Nose class... b) will not compile because the m1 method parameter should be named n, not x. 2. The Ears class...
More informationCopyright 2012, Oracle and/or its affiliates. All rights reserved.
1 Field guide to Java collections Mike Duigou (@mjduigou) Java Core Libraries 2 Required Reading Should have used most at some point List, Vector, ArrayList, LinkedList, Arrays.asList Set, HashSet, TreeSet
More informationIntroduction to Programming Using Java (98-388)
Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;
More informationAP CS Unit 7: Interfaces Exercises 1. Select the TRUE statement(s).
AP CS Unit 7: Interfaces Exercises 1. Select the TRUE statement(s). a) This code will not compile because a method cannot specify an interface as a parameter. public class Testing { public static void
More informationComputational Expression
Computational Expression ArrayList Iterators Janyl Jumadinova 7-14 November, 2018 Janyl Jumadinova Computational Expression 7-14 November, 2018 1 / 11 Collections Collection: an object that stores data;
More informationCS Week 14. Jim Williams, PhD
CS 200 - Week 14 Jim Williams, PhD This Week 1. Final Exam: Conflict Alternatives Emailed 2. Team Lab: Object Oriented Space Game 3. BP2 Milestone 3: Strategy 4. Lecture: More Classes and Additional Topics
More informationContents. Figures. Tables. Examples. Foreword. Preface. 1 Basics of Java Programming 1. xix. xxi. xxiii. xxvii. xxix
PGJC4_JSE8_OCA.book Page ix Monday, June 20, 2016 2:31 PM Contents Figures Tables Examples Foreword Preface xix xxi xxiii xxvii xxix 1 Basics of Java Programming 1 1.1 Introduction 2 1.2 Classes 2 Declaring
More informationJava Collections Framework reloaded
Java Collections Framework reloaded October 1, 2004 Java Collections - 2004-10-01 p. 1/23 Outline Interfaces Implementations Ordering Java 1.5 Java Collections - 2004-10-01 p. 2/23 Components Interfaces:
More informationControl Structures. A program can proceed: Sequentially Selectively (branch) - making a choice Repetitively (iteratively) - looping
Control Structures A program can proceed: Sequentially Selectively (branch) - making a choice Repetitively (iteratively) - looping Conditional Execution if is a reserved word The most basic syntax for
More informationOptimization of Preference Queries with Multiple Constraints
Optimization of Preference Queries with Multiple Constraints Markus Endres and Werner Kießling Speaker: Timotheus Preisinger University of Augsburg Germany 2nd International Workshop on Personalized Access,
More information1B1a Arrays. Arrays. Indexing. Naming arrays. Why? Using indexing. 1B1a Lecture Slides. Copyright 2003, Graham Roberts 1
Ba Arrays Arrays A normal variable holds value: An array variable holds a collection of values: 4 Naming arrays An array has a single name, so the elements are numbered or indexed. 0 3 4 5 Numbering starts
More informationList are immutable Lists have recursive structure Lists are homogeneous
WORKING WITH LISTS val fruit = List("apples", "oranges", "pears") val nums: List[Int] = List(1, 2, 3, 4) val diag3 = List( List(1, 0, 0), List(0, 1, 0), List(0, 0, 1) ) val empty = List() List are immutable
More informationJava 8 Lambdas & Streams Angelika Langer
Java 8 Lambdas & Streams Angelika Langer objective understand lambda expressions learn about method references explore the stream API get a feeling for its performance model Lambdas & Streams in Java 8
More informationIntroduction to Computer Science I
Introduction to Computer Science I Iterators ArrayList Janyl Jumadinova October 31, 2016 Iterators One of the most useful operations for any collection is the ability to run through each of the elements
More informationQuestion 1. [5 points] What output is printed by the following program (which begins on the left and continues on the right)?
CS 201, Summer 2015 August 13th Final Exam Name: Question 1. [5 points] What output is printed by the following program (which begins on the left and continues on the right)? public class Q1 { public static
More informationCollections Questions
Collections Questions https://www.journaldev.com/1330/java-collections-interview-questions-and-answers https://www.baeldung.com/java-collections-interview-questions https://www.javatpoint.com/java-collections-interview-questions
More informationThe ArrayList class CSC 123 Fall 2018 Howard Rosenthal
The ArrayList class CSC 123 Fall 2018 Howard Rosenthal Lesson Goals Describe the ArrayList class Discuss important methods of this class Describe how it can be used in modeling Much of the information
More information11-1. Collections. CSE 143 Java. Java 2 Collection Interfaces. Goals for Next Several Lectures
Collections CSE 143 Java Collections Most programs need to store and access collections of data Collections are worth studying because... They are widely useful in programming They provide examples of
More informationCore Java Syllabus. Overview
Core Java Syllabus Overview Java programming language was originally developed by Sun Microsystems which was initiated by James Gosling and released in 1995 as core component of Sun Microsystems' Java
More informationMore non-primitive types Lesson 06
CSC110 2.0 Object Oriented Programming Ms. Gnanakanthi Makalanda Dept. of Computer Science University of Sri Jayewardenepura More non-primitive types Lesson 06 1 2 Outline 1. Two-dimensional arrays 2.
More informationdef order(food): food = food.upper() print( Could I have a big + food + please? ) return fresh + food
CSCI 1101B Lists Warm-up Exercise def order(food): food = food.upper() print( Could I have a big + food + please? ) return fresh + food food = order( pasta ) After this program runs 1. What is the global
More informationAP CS Unit 7: Interfaces. Programs
AP CS Unit 7: Interfaces. Programs You cannot use the less than () operators with objects; it won t compile because it doesn t always make sense to say that one object is less than
More informationLecture Transcript While and Do While Statements in C++
Lecture Transcript While and Do While Statements in C++ Hello and welcome back. In this lecture we are going to look at the while and do...while iteration statements in C++. Here is a quick recap of some
More informationCOURSE 5 PROGRAMMING III OOP. JAVA LANGUAGE
COURSE 5 PROGRAMMING III OOP. JAVA LANGUAGE PREVIOUS COURSE CONTENT Generics Defining a generic Run-time behavior Collections List Set Map COUSE CONTENT Collections Utilities classes Aggregate Operations
More information09/02/2013 TYPE CHECKING AND CASTING. Lecture 5 CS2110 Spring 2013
1 TYPE CHECKING AND CASTING Lecture 5 CS2110 Spring 2013 1 Type Checking 2 Java compiler checks to see if your code is legal Today: Explore how this works What is Java doing? Why What will Java do if it
More information1. Is it currently raining in Tucson (4pts) a) Yes b) No? c) Don't know d) Couldn't know (not in Tucson)
1. Is it currently raining in Tucson (4pts) a) Yes b) No? c) Don't know d) Couldn't know (not in Tucson) 2. Use our familiar Node class (shown below with data and next instance variables) and this view
More informationExam 1 Prep. Dr. Demetrios Glinos University of Central Florida. COP3330 Object Oriented Programming
Exam 1 Prep Dr. Demetrios Glinos University of Central Florida COP3330 Object Oriented Programming Progress Exam 1 is a Timed Webcourses Quiz You can find it from the "Assignments" link on Webcourses choose
More informationObject-Oriented Design Lecture 13 CSU 370 Fall 2008 (Pucella) Friday, Oct 31, 2008
Object-Oriented Design Lecture 13 CSU 370 Fall 2008 (Pucella) Friday, Oct 31, 2008 Laziness For this lecture, I want to return to something that came up during the last homework, the third homework where
More informationWeiss Chapter 1 terminology (parenthesized numbers are page numbers)
Weiss Chapter 1 terminology (parenthesized numbers are page numbers) assignment operators In Java, used to alter the value of a variable. These operators include =, +=, -=, *=, and /=. (9) autoincrement
More informationObject-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018
Object-oriented programming 1 and data-structures CS/ENGRD 2110 SUMMER 2018 Lecture 1: Types and Control Flow http://courses.cs.cornell.edu/cs2110/2018su Lecture 1 Outline 2 Languages Overview Imperative
More informationRepresentation Invariants and Abstraction Functions
Representation Invariants and Abstraction Functions Outline Reasoning about ADTs Representation invariants (rep invariants) Representation exposure Checking rep invariants Abstraction functions CSCI 2600
More informationCO Java SE 8: Fundamentals
CO-83527 Java SE 8: Fundamentals Summary Duration 5 Days Audience Application Developer, Developer, Project Manager, Systems Administrator, Technical Administrator, Technical Consultant and Web Administrator
More informationCSE 143 Lecture 4. Preconditions
CSE 143 Lecture 4 Exceptions and ArrayList slides created by Marty Stepp http://www.cs.washington.edu/143/ Preconditions precondition: Something your method assumes is true at the start of its execution.
More informationClass Libraries. Readings and References. Java fundamentals. Java class libraries and data structures. Reading. Other References
Reading Readings and References Class Libraries CSE 142, Summer 2002 Computer Programming 1 Other References» The Java tutorial» http://java.sun.com/docs/books/tutorial/ http://www.cs.washington.edu/education/courses/142/02su/
More informationMIS2502: Review for Exam 2. Jing Gong
MIS2502: Review for Exam 2 Jing Gong gong@temple.edu http://community.mis.temple.edu/gong Overview Date/Time: Friday, October 30, 3:00 3:50 pm Place: Regular classroom (Alter Hall 232) Please arrive 5
More informationLists using LinkedList
Lists using LinkedList 1 LinkedList Apart from arrays and array lists, Java provides another class for handling lists, namely LinkedList. An instance of LinkedList is called a linked list. The constructors
More informationpublic static void negate2(list<integer> t)
See the 2 APIs attached at the end of this worksheet. 1. Methods: Javadoc Complete the Javadoc comments for the following two methods from the API: (a) / @param @param @param @return @pre. / public static
More informationBinghamton University. CS-140 Fall Problem Solving. Creating a class from scratch
Problem Solving Creating a class from scratch 1 Recipe for Writing a Class 1. Write the class boilerplate stuff 2. Declare Fields 3. Write Creator(s) 4. Write accessor methods 5. Write mutator methods
More informationThis exam is open book. Each question is worth 3 points.
This exam is open book. Each question is worth 3 points. Page 1 / 15 Page 2 / 15 Page 3 / 12 Page 4 / 18 Page 5 / 15 Page 6 / 9 Page 7 / 12 Page 8 / 6 Total / 100 (maximum is 102) 1. Are you in CS101 or
More informationCITS1001 week 4 Grouping objects
CITS1001 week 4 Grouping objects Arran Stewart March 20, 2018 1 / 31 Overview In this lecture, we look at how can group objects together into collections. Main concepts: The ArrayList collection Processing
More informationTony Valderrama, SIPB IAP 2010
Today Java API java.util java.io More OOP Generics Enum.jar files JNI Q & A Announcements Course website: http://sipb.mit.edu/iap/java/ Email: sipb-iap-java@mit.edu package java.io Images from the Java
More informationPython Programming: Lecture 2 Data Types
Python Programming: Lecture 2 Data Types Lili Dworkin University of Pennsylvania Last Week s Quiz 1..pyc files contain byte code 2. The type of math.sqrt(9)/3 is float 3. The type of isinstance(5.5, float)
More information6.005 Elements of Software Construction Fall 2008
MIT OpenCourseWare http://ocw.mit.edu 6.005 Elements of Software Construction Fall 2008 For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms. 6.005 elements
More informationCS 10: Problem solving via Object Oriented Programming. Streams
CS 10: Problem solving via Object Oriented Programming Streams Agenda 1. Streaming data 2. Java streams 2 Streams allow us to process things as they come Stream movie vs. file Stream (Ne1lix) Data produc=on
More informationCSE 143. Computer Programming II
Adam Blank Lecture 15 Spring 2015 CSE 143 Computer Programming II CSE 143: Computer Programming II More Interfaces & Iterators Today s Goals 1 We begin with ArrayIntList & LinkedIntList. Our goals are:
More informationAdvanced Java Concepts Unit 2: Linked Lists.
Advanced Java Concepts Unit 2: Linked Lists. The List interface defines the structure of a linear collection. Here are some of its methods. boolean add( E element ) Appends the element to the end of the
More information20761 Querying Data with Transact SQL
Course Overview The main purpose of this course is to give students a good understanding of the Transact-SQL language which is used by all SQL Server-related disciplines; namely, Database Administration,
More information