#How to remove duplicate characters from a string in java
Explore tagged Tumblr posts
topjavatutorial-blog · 7 years ago
Text
Java program to remove duplicate characters from a String
Java program to remove duplicate characters from a String
In this article, we will discuss how to remove duplicate characters from a String. Here is the expected output for some given inputs : Input : topjavatutorial Output : topjavuril Input : hello Output : helo The below program that loops through each character of the String checking if it has already been encountered and ignoring it if the condition is true. package com.topjavatutorial; public…
View On WordPress
0 notes
ishjunblogs · 3 years ago
Link
0 notes
bruhcardi · 5 years ago
Text
Database Interview Questions for java
What’s the Difference between a Primary Key and a Unique Key?
Both primary key and unique key enforce uniqueness of the column on which they are defined. But by default, the primary key creates a clustered index on the column, whereas unique key creates a non-clustered index by default. Another major difference is that primary key doesn’t allow NULLs, but unique key allows one NULL only. Primary Key is the address of data and unique key may not.
What are the Different Index Configurations a Table can have?
A table can have one of the following index configurations:
No indexes A clustered index A clustered index and many non-clustered indexes A non-clustered index Many non-clustered indexes
What is Difference between DELETE and TRUNCATE Commands?
The DELETE command is used to remove rows from a table. A WHERE clause can be used to only remove some rows. If no WHERE condition is specified, all rows will be removed. After performing a DELETE operation you need to COMMIT or ROLLBACK the transaction to make the change permanent or to undo it. Note that this operation will cause all DELETE triggers on the table to fire.
TRUNCATE removes all rows from a table. The operation cannot be rolled back and no triggers will be fired. As such, TRUCATE is faster and doesn’t use as much undo space as a DELETE.
TRUNCATE
TRUNCATE is faster and uses fewer system and transaction log resources than DELETE. TRUNCATE removes the data by deallocating the data pages used to store the table’s data, and only the page deallocations are recorded in the transaction log. TRUNCATE removes all the rows from a table, but the table structure, its columns, constraints, indexes and so on remains. The counter used by an identity for new rows is reset to the seed for the column. You cannot use TRUNCATE TABLE on a table referenced by a FOREIGN KEY constraint. Using T-SQL – TRUNCATE cannot be rolled back unless it is used in TRANSACTION. OR TRUNCATE can be rolled back when used with BEGIN … END TRANSACTION using T-SQL. TRUNCATE is a DDL Command. TRUNCATE resets the identity of the table.
DELETE
DELETE removes rows one at a time and records an entry in the transaction log for each deleted row. DELETE does not reset Identity property of the table. DELETE can be used with or without a WHERE clause DELETE activates Triggers if defined on table. DELETE can be rolled back. DELETE is DML Command. DELETE does not reset the identity of the table.
What are Different Types of Locks?
Shared Locks: Used for operations that do not change or update data (read-only operations), such as a SELECT statement. Update Locks: Used on resources that can be updated. It prevents a common form of deadlock that occurs when multiple sessions are reading, locking, and potentially updating resources later. Exclusive Locks: Used for data-modification operations, such as INSERT, UPDATE, or DELETE. It ensures that multiple updates cannot be made to the same resource at the same time.
What are Pessimistic Lock and Optimistic Lock?
Optimistic Locking is a strategy where you read a record, take note of a version number and check that the version hasn’t changed before you write the record back. If the record is dirty (i.e. different version to yours), then you abort the transaction and the user can re-start it. Pessimistic Locking is when you lock the record for your exclusive use until you have finished with it. It has much better integrity than optimistic locking but requires you to be careful with your application design to avoid Deadlocks.
What is the Difference between a HAVING clause and a WHERE clause?
They specify a search condition for a group or an aggregate. But the difference is that HAVING can be used only with the SELECT statement. HAVING is typically used in a GROUP BY clause. When GROUP BY is not used, HAVING behaves like a WHERE clause. Having Clause is basically used only with the GROUP BY function in a query, whereas WHERE Clause is applied to each row before they are part of the GROUP BY function in a query.
What is NOT NULL Constraint?
A NOT NULL constraint enforces that the column will not accept null values. The not null constraints are used to enforce domain integrity, as the check constraints.
What is the difference between UNION and UNION ALL?
UNION The UNION command is used to select related information from two tables, much like the JOIN command. However, when using the UNION command all selected columns need to be of the same data type. With UNION, only distinct values are selected.
UNION ALL The UNION ALL command is equal to the UNION command, except that UNION ALL selects all values.
The difference between UNION and UNION ALL is that UNION ALL will not eliminate duplicate rows, instead it just pulls all rows from all the tables fitting your query specifics and combines them into a table.
What is B-Tree?
The database server uses a B-tree structure to organize index information. B-Tree generally has following types of index pages or nodes:
Root node: A root node contains node pointers to only one branch node.
Branch nodes: A branch node contains pointers to leaf nodes or other branch nodes, which can be two or more.
Leaf nodes: A leaf node contains index items and horizontal pointers to other leaf nodes, which can be many.
What are the Advantages of Using Stored Procedures?
Stored procedure can reduced network traffic and latency, boosting application performance. Stored procedure execution plans can be reused; they staying cached in SQL Server’s memory, reducing server overhead. Stored procedures help promote code reuse. Stored procedures can encapsulate logic. You can change stored procedure code without affecting clients. Stored procedures provide better security to your data.
What is SQL Injection? How to Protect Against SQL Injection Attack? SQL injection is an attack in which malicious code is inserted into strings that are later passed to an instance of SQL Server for parsing and execution. Any procedure that constructs SQL statements should be reviewed for injection vulnerabilities because SQL Server will execute all syntactically valid queries that it receives. Even parameterized data can be manipulated by a skilled and determined attacker. Here are few methods which can be used to protect again SQL Injection attack:
Use Type-Safe SQL Parameters Use Parameterized Input with Stored Procedures Use the Parameters Collection with Dynamic SQL Filtering Input parameters Use the escape character in LIKE clause Wrapping Parameters with QUOTENAME() and REPLACE()
What is the Correct Order of the Logical Query Processing Phases?
The correct order of the Logical Query Processing Phases is as follows: 1. FROM 2. ON 3. OUTER 4. WHERE 5. GROUP BY 6. CUBE | ROLLUP 7. HAVING 8. SELECT 9. DISTINCT 10. TOP 11. ORDER BY
What are Different Types of Join?
Cross Join : A cross join that does not have a WHERE clause produces the Cartesian product of the tables involved in the join. The size of a Cartesian product result set is the number of rows in the first table multiplied by the number of rows in the second table. The common example is when company wants to combine each product with a pricing table to analyze each product at each price. Inner Join : A join that displays only the rows that have a match in both joined tables is known as inner Join. This is the default type of join in the Query and View Designer. Outer Join : A join that includes rows even if they do not have related rows in the joined table is an Outer Join. You can create three different outer join to specify the unmatched rows to be included: Left Outer Join: In Left Outer Join, all the rows in the first-named table, i.e. “left” table, which appears leftmost in the JOIN clause, are included. Unmatched rows in the right table do not appear. Right Outer Join: In Right Outer Join, all the rows in the second-named table, i.e. “right” table, which appears rightmost in the JOIN clause are included. Unmatched rows in the left table are not included. Full Outer Join : In Full Outer Join, all the rows in all joined tables are included, whether they are matched or not. Self Join : This is a particular case when one table joins to itself with one or two aliases to avoid confusion. A self join can be of any type, as long as the joined tables are the same. A self join is rather unique in that it involves a relationship with only one table. The common example is when company has a hierarchal reporting structure whereby one member of staff reports to another. Self Join can be Outer Join or Inner Join.
What is a View?
A simple view can be thought of as a subset of a table. It can be used for retrieving data as well as updating or deleting rows. Rows updated or deleted in the view are updated or deleted in the table the view was created with. It should also be noted that as data in the original table changes, so does the data in the view as views are the way to look at parts of the original table. The results of using a view are not permanently stored in the database. The data accessed through a view is actually constructed using standard T-SQL select command and can come from one to many different base tables or even other views.
What is an Index?
An index is a physical structure containing pointers to the data. Indices are created in an existing table to locate rows more quickly and efficiently. It is possible to create an index on one or more columns of a table, and each index is given a name. The users cannot see the indexes; they are just used to speed up queries. Effective indexes are one of the best ways to improve performance in a database application. A table scan happens when there is no index available to help a query. In a table scan, the SQL Server examines every row in the table to satisfy the query results. Table scans are sometimes unavoidable, but on large tables, scans have a terrific impact on performance.
Can a view be updated/inserted/deleted? If Yes – under what conditions ?
A View can be updated/deleted/inserted if it has only one base table if the view is based on columns from one or more tables then insert, update and delete is not possible.
What is a Surrogate Key?
A surrogate key is a substitution for the natural primary key. It is just a unique identifier or number for each row that can be used for the primary key to the table. The only requirement for a surrogate primary key is that it should be unique for each row in the table. It is useful because the natural primary key can change and this makes updates more difficult. Surrogated keys are always integer or numeric.
How to remove duplicates from table? ? 1 2 3 4 5 6 7 8 9
DELETE FROM TableName WHERE ID NOT IN (SELECT MAX(ID) FROM TableName GROUP BY Column1, Column2, Column3, ------ Column..n HAVING MAX(ID) IS NOT NULL)
Note : Where Combination of Column1, Column2, Column3, … Column n define the uniqueness of Record.
How to fine the N’th Maximum salary using SQL query?
Using Sub query ? 1 2 3 4 5 6
SELECT * FROM Employee E1 WHERE (N-1) = ( SELECT COUNT(DISTINCT(E2.Salary)) FROM Employee E2 WHERE E2.Salary > E1.Salary )
Another way to get 2’nd maximum salary ? 1
Select max(Salary) From Employee e where e.sal < ( select max(sal) from employee );
0 notes
felord · 6 years ago
Text
SOLVED:P2: Interactive PlayList Analysis Solution
In this assignment, you will develop an application that manages a user's songs in a simplified playlist. Objectives Write a class with a main method (PlayList). Use an existing, custom class (Song). Use classes from the Java standard library. Work with numeric data. Work with standard input and output. Specification Existing class that you will use: Song.java Class that you will create: PlayList.java Song (provided class) You do not need to modify this class. You will just use it in your PlayList driver class. You are given a class named Song that keeps track of the details about a song. Each song instance will keep track of the following data. Title of the song. The song title must be specified when the song is created. Artist of the song. The song artist must be specified when the song is created. The play time (in seconds) of the song. The play time must be specified when the song is created. The file path of the song. The file path must be specified when the song is created. The play count of the song (e.g. how many times has the song been played). This is set to 0 by default when the song is created. The Song class has the following methods available for you to use: public Song(String title, String artist, int playTime, String filePath) -- (The Constructor) public String getTitle() public String getArtist() public int getPlayTime() public String getFilePath() public void play() public void stop() public String toString() To find out what each method does, look at the documentation for the Song class: java docs for Song class PlayList (the driver class) You will write a class called PlayList. It is the driver class, meaning, it will contain the main method. In this class, you will gather song information from the user by prompting and reading data from the command line. Then, you will store the song information by creating song objects from the given data. You will use the methods available in the song class to extract data from the song objects, calculate statistics for song play times, and print the information to the user. Finally, you will use conditional statements to order songs by play time. The ordered "playlist" will be printed to the user. Your PlayList code should not duplicate any data or functionality that belongs to the Song objects. Make sure that you are accessing data using the Song methods. Do NOT use a loop or arrays to generate your Songs. We will discuss how to do this later, but please don't over complicate things now. If you want to do something extra, see the extra credit section below. User input Console input should be handled with a Scanner object. Create a Scanner using the standard input as follows: Scanner in = new Scanner(System.in); You should never make more than one Scanner from System.in in any program. Creating more than one Scanner from System.in crashes the script used to test the program. There is only one keyboard; there should only be one Scanner. Your program will prompt the user for the following values and read the user's input from the keyboard. A String for the song title. A String for the song artist. A String for the song play time (converted to an int later). A String for the song file path. Here is a sample input session for one song. Your program must read input in the order below. If it doesn't, it will fail our tests when grading. Enter title: Big Jet Plane Enter artist: Julia Stone Enter play time (mm:ss): 3:54 Enter file name: sounds/westernBeat.wav You can use the nextLine() method of the Scanner class to read each line of input. Creating Song objects from input As you read in the values for each song, create a new Song object using the input values. Use the following process to create each new song. Read the input values from the user into temporary variables. You will need to do some manipulation of the playing time data. The play time will be entered in the format mm:ss, where mm is the number of minutes and ss is the number of seconds. You will need to convert this string value to the total number of seconds before you can store it in your Song object. (Hint: use the String class's indexOf() method to find the index of the ':' character, then use the substring() method to get the minutes and seconds values.) All other input values are String objects, so you can store them directly in your Song object. Use the Song constructor to instantiate a new song, passing in the variables containing the title, artist, play time, and file path. Because a copy of the values will be stored in your song objects, you can re-use the same temporary variables when reading input for the next song. Before moving to the next step, print your song objects to make sure everything looks correct. To print a song, you may use the provided toString method. Look at the Song documentation for an example of how to print a song. NOTE: Each Song instance you create will store its own data, so you will use the methods of the Song class to get that data when you need it. Don't use the temporary variables that you created for reading input from the user. For example, once you create a song, you may retrieve the title using song1.getTitle(); Calculate the average play time. Use the getPlayTime() method to retrieve the play time of each song and calculate the average play time in seconds. Print the average play time formatted to two decimal places. Format the output as shown in example below. Average play time: 260.67 Use the DecimalFormat formatter to print the average. You may use this Find the song with play time closest to 4 minutes Determine which song has play time closest to 4 minutes. Print the title of the song formatted as shown in the output below. Song with play time closest to 240 secs is: Big Jet Plane Build a sorted play list Build a play list of the songs from the shortest to the longest play time and print the songs in order. To print the formatted song data, use the toString() method in the Song class. Print the play list as shown in the output below. ============================================================================== Title Artist File Name Play Time ============================================================================== Where you end Moby sounds/classical.wav 198 Big Jet Plane Julia Stone sounds/westernBeat.wav 234 Last Tango in Paris Gotan Project sounds/newAgeRhythm.wav 350 ============================================================================== Extra Credit (5 points) You may notice that you are repeating the same code to read in the song data from the user for each song (Yuck! This would get really messy if we had 10 songs). Modify your main method to use a loop to read in the songs from the user. As you read and create new songs, you will need to store your songs in an ArrayList. This can be quite challenging if you have never used ArrayLists before, so we recommend saving a backup of your original implementation before attempting the extra credit. Getting Started Create a new Eclipse project for this assignment and import Song.java into your project. Create a new Java class called PlayList and add a main method. Read the Song documentation and (if you are feeling adventurous) look through the Song.java file to familiarize yourself with what it contains and how it works before writing any code of your own. Start implementing your Song class according to the specifications. Test often! Run your program after each task so you can find and fix problems early. It is really hard for anyone to track down problems if the code was not tested along the way. Sample Input/Output Make sure you at least test all of the following inputs. Last Tango in Paris Gotan Project 05:50 sounds/newAgeRhythm.wav Where you end Moby 3:18 sounds/classical.wav Big Jet Plane Julia Stone 3:54 sounds/westernBeat.wav Where you end Moby 3:18 sounds/classical.wav Last Tango in Paris Gotan Project 05:50 sounds/newAgeRhythm.wav Big Jet Plane Julia Stone 3:54 sounds/westernBeat.wav Big Jet Plane Julia Stone 3:54 sounds/westernBeat.wav Last Tango in Paris Gotan Project 05:50 sounds/newAgeRhythm.wav Where you end Moby 3:18 sounds/classical.wav Submitting Your Project Testing Once you have completed your program in Eclipse, copy your Song.java, PlayList.java and README files into a directory on the onyx server, with no other files (if you did the project on your computer). Test that you can compile and run your program from the console in the lab to make sure that it will run properly for the grader. javac PlayList.java java PlayList Documentation If you haven't already, add a javadoc comment to your program. It should be located immediately before the class header. If you forgot how to do this, go look at the Documenting Your Program section from lab . Have a class javadoc comment before the class (as you did in the first lab) Your class comment must include the @author tag at the end of the comment. This will list you as the author of your software when you create your documentation. Include a plain-text file called README that describes your program and how to use it. Expected formatting and content are described in README_TEMPLATE. See README_EXAMPLE for an example. Submission You will follow the same process for submitting each project. Open a console and navigate to the project directory containing your source files, Remove all the .class files using the command, rm *.class. In the same directory, execute the submit command for your section as shown in the following table. Look for the success message and timestamp. If you don't see a success message and timestamp, make sure the submit command you used is EXACTLY as shown. Required Source Files Required files (be sure the names match what is here exactly): PlayList.java (main class) Song.java (provided class) README Section Instructor Submit Command 1 Luke Hindman (TuTh 1:30 - 2:45) submit lhindman cs121-1 p2 2 Greg Andersen (TuTh 9:00 - 10:15) submit gandersen cs121-2 p2 3 Luke Hindman (TuTh 10:30 - 11:45) submit lhindman cs121-3 p2 4 Marissa Schmidt (TuTh 4:30 - 5:45) submit marissa cs121-4 p2 5 Jerry Fails (TuTh 1:30 - 2:45) submit jfails cs121-5 p2 After submitting, you may check your submission using the "check" command. In the example below, replace submit -check Read the full article
0 notes
iyarpage · 7 years ago
Text
Structured JUnit 5 testing
Automated tests, in Java most commonly written with JUnit, are critical to any reasonable software project. Some even say that test code is more important than production code, because it’s easier to recreate the production code from the tests than the other way around. Anyway, they are valuable assets, so it’s necessary to keep them clean.
Adding new tests is something you’ll be doing every day, but hold yourself from getting into a write-only mode: Its overwhelmingly tempting to simply duplicate an existing test method and change just some details for the new test. But when you refactor the production code, you often have to change some test code, too. If this is spilled all over your tests, you will have a hard time; and what’s worse, you will be tempted to not do the refactoring or even stop writing tests. So also in your test code you’ll have to reduce code duplication to a minimum from the very beginning. It’s so little extra work to do now, when you’re into the subject, that it will amortize in no time.
JUnit 5 gives us some opportunities to do this even better, and I’ll show you some techniques here.
Any examples I can come up with are necessarily simplified, as they can’t have the full complexity of a real system. So bear with me while I try to contrive examples with enough complexity to show the effects; and allow me to challenge your fantasy that some things, while they are just over-engineered at this scale, will prove useful when things get bigger.
If you like, you can follow the refactorings done here by looking at the tests in this Git project. They are numbered to match the order presented here.
Example: Testing a parser with three methods for four documents
Let’s take a parser for a stream of documents (like in YAML) as an example test subject. It has three methods:
public class Parser { /** * Parse the one and only document in the input. * * @throws ParseException if there is none or more than one. */ public static Document parseSingle(String input); /** * Parse only the first document in the input. * * @throws ParseException if there is none. */ public static Document parseFirst(String input); /** Parse the list of documents in the input; may be empty, too. */ public static Stream parseAll(String input); }
We use static methods only to make the tests simpler; normally this would be a normal object with member methods.
We write tests for four input files (not to make things too complex): one is empty, one contains a document with only one space character, one contains a single document containing only a comment, and one contains two documents with each only containing a comment. That makes a total of 12 tests looking similar to this one:
class ParserTest { @Test void shouldParseSingleInDocumentOnly() { String input = "# test comment"; Document document = Parser.parseSingle(input); assertThat(document).isEqualTo(new Document().comment(new Comment().text("test comment"))); } }
Following the BDD given-when-then schema, I first have a test setup part (given), then an invocation of the system under test (when), and finally a verification of the outcome (then). These three parts are delimited with empty lines.
For the verification, I use AssertJ.
To reduce duplication, we extract the given and when parts into methods:
class ParserTest { @Test void shouldParseSingleInDocumentOnly() { String input = givenCommentOnlyDocument(); Document document = whenParseSingle(input); assertThat(document).isEqualTo(COMMENT_ONLY_DOCUMENT); } }
Or when the parser is expected to fail:
class ParserTest { @Test void shouldParseSingleInEmpty() { String input = givenEmptyDocument(); ParseException thrown = whenParseSingleThrows(input); assertThat(thrown).hasMessage("expected exactly one document, but found 0"); } }
The given... methods are called three times each, once for every parser method. The when... methods are called four times each, once for every input document, minus the cases where the tests expect exceptions. There is actually not so much reuse for the then... methods; we only extract some constants for the expected documents here, e.g. COMMENT_ONLY.
But reuse is not the most important reason to extract a method. It’s more about hiding complexity and staying at a single level of abstraction. As always, you’ll have to find the right balance: Is whenParseSingle(input) better than Parser.parseSingle(input)? It’s so simple and unlikely that you will ever have to change it by hand, that it’s probably better to not extract it. If you want to go into more detail, read the Clean Code book by Robert C. Martin, it’s worth it!
You can see that the given... methods all return an input string, while all when... methods take that string as an argument. When tests get more complex, they produce or require more than one object, so you’ll have to pass them via fields. But normally I wouldn’t do this in such a simple case. Let’s do that here anyway, as a preparation for the next step:
class ParserTest { private String input; @Test void shouldParseAllInEmptyDocument() { givenEmptyDocument(); Stream stream = whenParseAll(); assertThat(stream.documents()).isEmpty(); } private void givenEmptyDocument() { input = ""; } private Stream whenParseAll() { return Parser.parseAll(input); } }
Adding structure
It would be nice to group all tests with the same input together, so it’s easier to find them in a larger test base, and to more easily see if there are some setups missing or duplicated. To do so in JUnit 5, you can surround all tests that call, e.g., givenTwoCommentOnlyDocuments() with an inner class GivenTwoCommentOnlyDocuments. To have JUnit still recognize the nested test methods, we’ll have to add a @Nested annotation:
class ParserTest { @Nested class GivenOneCommentOnlyDocument { @Test void shouldParseAllInDocumentOnly() { givenOneCommentOnlyDocument(); Stream stream = whenParseAll(); assertThat(stream.documents()).containsExactly(COMMENT_ONLY); } } }
In contrast to having separate top-level test classes, JUnit runs these tests as nested groups, so we see the test run structured like this:
Nice, but we can go a step further. Instead of calling the respective given... method from each test method, we can call it in a @BeforeEach setup method, and as there is now only one call for each given... method, we can inline it:
@Nested class GivenTwoCommentOnlyDocuments { @BeforeEach void givenTwoCommentOnlyDocuments() { input = "# test comment\n---\n# test comment 2"; } }
We could have a little bit less code (which is generally a good thing) by using a constructor like this:
@Nested class GivenTwoCommentOnlyDocuments { GivenTwoCommentOnlyDocuments() { input = "# test comment\n---\n# test comment 2"; } }
…or even an anonymous initializer like this:
@Nested class GivenTwoCommentOnlyDocuments { { input = "# test comment\n---\n# test comment 2"; } }
But I prefer methods to have names that say what they do, and as you can see in the first variant, setup methods are no exception. I sometimes even have several @BeforeEach methods in a single class, when they do separate setup work. This gives me the advantage that I don’t have to read the method body to understand what it does, and when some setup doesn’t work as expected, I can start by looking directly at the method that is responsible for that. But I must admit that this is actually some repetition in this case; probably it’s a matter of taste.
Now the test method names still describe the setup they run in, i.e. the InDocumentOnly part in shouldParseSingleInDocumentOnly. In the code structure as well as in the output provided by the JUnit runner, this is redundant, so we should remove it: shouldParseSingle.
The JUnit runner now looks like this:
Most real world tests share only part of the setup with other tests. You can extract the common setup and simply add the specific setup in each test. I often use objects with all fields set up with reasonable dummy values, and only modify those relevant for each test, e.g. setting one field to null to test that specific outcome. Just make sure to express any additional setup steps in the name of the test, or you may overlook it.
When things get more complex, it’s probably better to nest several layers of Given... classes, even when they have only one test, just to make all setup steps visible in one place, the class names, and not some in the class names and some in the method names.
When you start extracting your setups like this, you will find that it gets easier to concentrate on one thing at a time: within one test setup, it’s easier to see if you have covered all requirements in this context; and when you look at the setup classes, it’s easier to see if you have all variations of the setup covered.
Extracting when...
The next step gets a little bit more involved and there are some forces to balance. If it’s too difficult to grasp now, you can also simply start by just extracting Given... classes as described above. When you’re fluent with that pattern and feel the need for more, you can return here and continue to learn.
You may have noticed that the four classes not only all have the same three test method names (except for the tests that catch exceptions), these three also call exactly the same when... methods; they only differ in the checks performed. This is, too, code duplication that has a potential to become harmful when the test code base gets big. In this carefully crafted example, we have a very symmetric set of three when... methods we want to call; this not always the case, so it’s not something you’ll be doing with every test class. But it’s good to know the technique, just in case. Let’s have a look at how it works.
We can extract an abstract class WhenParseAllFirstAndSingle to contain the three test methods that delegate the actual verification to abstract verify... methods. As the when... methods are not reused any more and the test methods have the same level of abstraction, we can also inline these.
class ParserTest { private String input; abstract class WhenParseAllFirstAndSingle { @Test void whenParseAll() { Stream stream = Parser.parseAll(input); verifyParseAll(stream); } protected abstract void verifyParseAll(Stream stream); } @Nested class GivenOneCommentOnlyDocument extends WhenParseAllFirstAndSingle { @BeforeEach void givenOneCommentOnlyDocument() { input = "# test comment"; } @Override protected void verifyParseAll(Stream stream) { assertThat(stream.documents()).containsExactly(COMMENT_ONLY); } } }
The verification is done in the implementations, so we can’t say something like thenIsEmpty, we’ll need a generic name. thenParseAll would be misleading, so verify with the method called is a good name, e.g. verifyParseAll.
This extraction works fine for parseAll and the whenParseAll method is simple to understand. But, e.g., parseSingle throws an exception when there is more than one document. So the whenParseSingle test has to delegate the exception for verification, too.
Let’s introduce a second verifyParseSingleException method for that check. When we expect an exception, we don’t want to implement the verifyParseSingle method any more, and when we don’t expect an exception, we don’t want to implement the verifyParseSingleException, so we give both verify... methods a default implementation instead:
abstract class WhenParseAllFirstAndSingle { @Test void whenParseSingle() { ParseException thrown = catchThrowableOfType(() -> { Document document = Parser.parseSingle(input); verifyParseSingle(document); }, ParseException.class); if (thrown != null) verifyParseSingleException(thrown); } protected void verifyParseSingle(Document document) { fail("expected exception was not thrown. see the verifyParseSingleParseException method for details"); } protected void verifyParseSingleException(ParseException thrown) { fail("unexpected exception. see verifyParseSingle for what was expected", thrown); } }
That’s okay, but when you expect an exception, but it doesn’t throw and the verification fails instead, you’ll get a test failure that is not very helpful (stacktraces omitted):
java.lang.AssertionError: Expecting code to throw but threw instead
So we need an even smarter whenParseSingle:
abstract class WhenParseAllFirstAndSingle { @Test void whenParseSingle() { AtomicReference document = new AtomicReference<>(); ParseException thrown = catchThrowableOfType(() -> document.set(Parser.parseSingle(input)), ParseException.class); if (thrown != null) verifyParseSingleException(thrown); else verifyParseSingle(document.get()); } }
We have to pass the document from the closure back to the method level. I can’t use a simple variable, as it has to be assigned to null as a default, making it not-effectively-final, so the compiler won’t allow me to. Instead, I use an AtomicReference.
In this way, even when a test that expects a result throws an exception or vice versa, the error message is nice and helpful, e.g. when GivenEmptyDocument.whenParseSingle, which throws an exception, would expect an empty document, the exception would be:
AssertionError: unexpected exception. see verifyParseSingle for what was expected Caused by: ParseException: expected exactly one document, but found 0
All of this does add quite some complexity to the when... methods, bloating them from 2 lines to 6 with a non-trivial flow. Gladly, we can extract that to a generic whenVerify method that we can put into a test utilities class or even module.
abstract class WhenParseAllFirstAndSingle { @Test void whenParseSingle() { whenVerify(() -> Parser.parseSingle(input), ParseException.class, this::verifyParseSingle, this::verifyParseSingleException); } protected void verifyParseSingle(Document document) { fail("expected exception was not thrown. see the verifyParseSingleException method for details"); } protected void verifyParseSingleException(ParseException thrown) { fail("unexpected exception. see verifyParseSingle for what was expected", thrown); } /** * Calls the call and verifies the outcome. * If it succeeds, it calls verify. * If it fails with an exception of type exceptionClass, it calls verifyException. * * @param call The `when` part to invoke on the system under test * @param exceptionClass The type of exception that may be expected * @param verify The `then` part to check a successful outcome * @param verifyException The `then` part to check an expected exception * @param The type of the result of the `call` * @param The type of the expected exception */ public static void whenVerify( Supplier call, Class exceptionClass, Consumer verify, Consumer verifyException) { AtomicReference success = new AtomicReference<>(); E failure = catchThrowableOfType(() -> success.set(call.get()), exceptionClass); if (failure != null) verifyException.accept(failure); else verify.accept(success.get()); } }
The call to whenVerify is still far from easy to understand; it’s not clean code. I’ve added extensive JavaDoc to help the reader, but it still requires getting into. We can make the call more expressive by using a fluent builder, so it looks like this:
abstract class WhenParseAllFirstAndSingle { @Test void whenParseFirst() { when(() -> Parser.parseFirst(input)) .failsWith(ParseException.class).then(this::verifyParseFirstException) .succeeds().then(this::verifyParseFirst); } }
This makes the implementation explode, but the call is okay now.
As seen above, the tests themselves look nice, and that’s the most important part:
@Nested class GivenTwoCommentOnlyDocuments extends WhenParseAllFirstAndSingle { @BeforeEach void givenTwoCommentOnlyDocuments() { input = "# test comment\n---\n# test comment 2"; } @Override protected void verifyParseAll(Stream stream) { assertThat(stream.documents()).containsExactly(COMMENT_ONLY, COMMENT_ONLY_2); } @Override protected void verifyParseFirst(Document document) { assertThat(document).isEqualTo(COMMENT_ONLY); } @Override protected void verifyParseSingleException(ParseException thrown) { assertThat(thrown).hasMessage("expected exactly one document, but found 2"); } }
Multiple When... classes
If you have tests that only apply to a specific test setup, you can simply add them directly to that Given... class. If you have tests that apply to all test setups, you can add them to the When... super class. But there may be tests that apply to more than one setup, but not to all. In other words: you may want to have more than one When... superclass, which isn’t allowed in Java, but you can change the When... classes to interfaces with default methods. You’ll then have to change the fields used to pass test setup objects (the input String in our example) to be static, as interfaces can’t access non-static fields.
This looks like a simple change, but it can cause some nasty behavior: you’ll have to set these fields for every test, or you may accidentally inherit them from tests that ran before, i.e. your tests depend on the execution order. This will bend the time-space-continuum when you try to debug it, so be extra careful. It’s probably worth resetting everything to null in a top level @BeforeEach. Note that @BeforeEach methods from super classes are executed before those in sub classes, and the @BeforeEach of the container class is executed before everything else.
Otherwise, the change is straightforward:
class ParserTest { private static String input; @BeforeEach void resetInput() { input = null; } interface WhenParseAllFirstAndSingle { @Test default void whenParseAll() { Stream stream = Parser.parseAll(input); verifyParseAll(stream); } void verifyParseAll(Stream stream); } @Nested class GivenTwoCommentOnlyDocuments implements WhenParseAllFirstAndSingle { @BeforeEach void givenTwoCommentOnlyDocuments() { input = "# test comment\n---\n# test comment 2"; } // ... } }
Generic verifications
You may want to add generic verifications, e.g. YAML documents and streams should render toString equal to the input they where generated from. For the whenParseAll method, we add a verification line directly after the call to verifyParseAll:
interface WhenParseAllFirstAndSingle { @Test default void whenParseAll() { Stream stream = Parser.parseAll(input); verifyParseAll(stream); assertThat(stream).hasToString(input); } }
This is not so easy with the the other tests that are sometimes expected to fail (e.g. whenParseSingle). We chose an implementation using the whenVerify method (or the fluent builder) which we wanted to be generic. We could give up on that and inline it, but that would be sad.
Alternatively, we could add the verification to all overridden verifyParseFirst methods, but that would add duplication and it’d be easy to forget. What’s worse, each new verification we wanted to add, we’d have to add to every verify... method; this just doesn’t scale.
It’s better to call the generic verification directly after the abstract verification:
class ParserTest { interface WhenParseAllFirstAndSingle { @Test default void whenParseFirst() { when(() -> Parser.parseFirst(input)) .failsWith(ParseException.class).then(this::verifyParseFirstException) .succeeds().then(document -> { verifyParseFirst(document); verifyToStringEqualsInput(document); }); } default void verifyParseFirst(Document document) { fail("expected exception was not thrown. see the verifyParseFirstException method for details"); } default void verifyParseFirstException(ParseException thrown) { fail("unexpected exception. see verifyParseFirst for what was expected", thrown); } default void verifyToStringEqualsInput(Document document) { assertThat(document).hasToString(input); } } }
If you have more than one generic verification, it would be better to extract them to a verifyParseFirstGeneric method.
There is one last little nasty detail hiding in this test example: The verifyToStringEqualsInput(Document document) method has to be overridden in GivenTwoCommentOnlyDocuments, as only the first document from the stream is part of the toString, not the complete input. Make sure to briefly explain such things with a comment:
@Nested class GivenTwoCommentOnlyDocuments implements WhenParseAllFirstAndSingle { @Override public void verifyToStringEqualsInput(Document document) { assertThat(document).hasToString("# test comment"); // only first } }
tl;dr
To add structure to a long sequence of test methods in a class, group them according to their test setup in inner classes annotated as @Nested. Name these classes Given... and set them up in one or more @BeforeEach methods. Pass the objects that are set up and then used in your when... method in fields.
When there are sets of tests that should be executed in several setups (and given you prefer complexity over duplication), you may want to extract them to a super class, or (if you need more than one such set in one setup) to an interface with default methods (and make the fields you set up static). Name these classes or interfaces When... and delegate the verification to methods called verify + the name of the method invoked on the system under test.
I think grouping test setups is something you should do even in medium-sized test classes; it pays off quickly. Extracting sets of tests adds quite some complexity, so you probably should do it only when you have a significantly large set of tests to share between test setups, maybe 5 or more.
I hope this helps you reap the benefits JUnit 5 provides. I’d be glad to hear if you have any feedback from nitpicking to success stories.
Der Beitrag Structured JUnit 5 testing erschien zuerst auf codecentric AG Blog.
Structured JUnit 5 testing published first on https://medium.com/@koresol
0 notes
tutorialspointexamples · 7 years ago
Text
Java executor
Interfaces. Executor is a simple standardized interface for defining custom thread-like subsystems, including thread pools, asynchronous I/O, and lightweight task frameworks. Depending on which concrete Executor class is being used, tasks may execute in a newly created thread, an existing task-execution thread, or the thread calling execute, and may execute sequentially or concurrently. ExecutorService provides a more complete asynchronous task execution framework. An ExecutorService manages queuing and scheduling of tasks, and allows controlled shutdown. The ScheduledExecutorService subinterface and associated interfaces add support for delayed and periodic task execution. ExecutorServices provide methods arranging asynchronous execution of any function expressed as Callable, the result-bearing analog of Runnable. A Future returns the results of a function, allows determination of whether execution has completed, and provides a means to cancel execution. A RunnableFuture is a Future that possesses a run method that upon execution, sets its results. How to get sublist from arraylist in java? How to sort arraylist using comparator in java? How to reverse contents of arraylist java? How to shuffle elements in an arraylist in java? How to swap two elements in an arraylist java? how to read all elements in linkedlist by using iterator in java? How to copy or clone linked list in java? How to add all elements of a list to linkedlist in java? How to remove all elements from a linked list java? How to convert linked list to array in java? How to sort linkedlist using comparator in java? How to reverse linked list in java? How to shuffle elements in linked list in java? How to swap two elements in a linked list java? How to add an element at first and last position of linked list? How to get first element in linked list in java? How to get last element in linked list in java? How to iterate through linked list in reverse order? Linked list push and pop in java How to remove element from linkedlist in java? How to iterate through hashtable in java? How to copy map content to another hashtable? How to search a key in hashtable? How to search a value in hashtable? How to get all keys from hashtable in java? How to get entry set from hashtable in java? How to remove all elements from hashtable in java? Hash table implementation with equals and hashcode example How to eliminate duplicate keys user defined objects with Hashtable? How to remove duplicate elements from arraylist in java? How to remove duplicate elements from linkedlist in java? how to iterate a hashset in java? How to copy set content to another hashset in java? How to remove all elements from hashset in java? How to convert a hashset to an array in java? How to eliminate duplicate user defined objects from hashset in java? How to iterate a linkedhashset in java? How to convert linkedhashset to array in java? How to add all elements of a set to linkedhashset in java? How to remove all elements from linkedhashset in java? How to delete specific element from linkedhashset? How to check if a particular element exists in LinkedHashSet? How to eliminate duplicate user defined objects from linkedhashset? How to create a treeset in java? How to iterate treeset in java? How to convert list to treeset in java? How to remove duplicate entries from an array in java? How to find duplicate value in an array in java? How to get least value element from a set? How to get highest value element from a set? How to avoid duplicate user defined objects in TreeSet? How to create a hashmap in java? How to iterate hashmap in java? How to copy map content to another hashmap in java? How to search a key in hashmap in java? How to search a value in hashmap in java? How to get list of keys from hashmap java? How to get entryset from hashmap in java? How to delete all elements from hashmap in java? How to eliminate duplicate user defined objects as a key from hashmap? How to create a treemap in java? How to iterate treemap in java? How to copy map content to another treemap? How to search a key in treemap in java? How to search a value in treemap in java? How to get all keys from treemap in java? How to get entry set from treemap in java? How to remove all elements from a treeMap in java? How to sort keys in treemap by using comparator? How to get first key element from treemap in java? How to get last key element from treemap in java? How to reverse sort keys in a treemap? How to create a linkedhashmap in java? How to iterate linkedhashmap in java? How to search a key in linkedhashmap in java? How to search a value in linkedhashmap in java? How to remove all entries from linkedhashmap? How to eliminate duplicate user defined objects as a key from linkedhashmap? How to find user defined objects as a key from linkedhashmap? Java 8 functional interface. Java lambda expression. Java lambda expression hello world. Java lambda expression multiple parameters. Java lambda expression foreach loop. Java lambda expression multiple statements. Java lambda expression create thread. Java lambda expression comparator. Java lambda expression filter. Java method references. Java default method. Java stream api. Java create stream. Java create stream using list. Java stream filter. Java stream map. Java stream flatmap. Java stream distinct. Java forEach. Java collectors class. Java stringjoiner class. Java optional class. Java parallel array sorting. Java Base64. Java 8 type interface improvements. Java 7 type interface. Java 8 Date Time API. Java LocalDate class. Java LocalTime class. Java LocalDateTime class. Java MonthDay class. Java OffsetTime class. Java OffsetDateTime class. Java Clock class. Java ZonedDateTime class. Java ZoneId class. Java ZoneOffset class. Java Year class. Java YearMonth class. Java Period class. Java Duration class. Java Instant class. Java DayOfWeek class. Java Month enum. Java regular expression. Regex character classes. Java Regex Quantifiers. Regex metacharacters. Regex validate alphanumeric. Regex validate 10 digit number. Regex validate number. Regex validate alphabets. Regex validate username. Regex validate email. Regex validate password. Regex validate hex code. Regex validate image file extension. Regex validate ip address. Regex validate 12 hours time format. Regex validate 24 hours time format. Regex validate date. Regex validate html tag. Java Date class example. Java DateFormat class. Java SimpleDateFormat class. Java Calendar class. Java GregorianCalendar class. Java TimeZone class. Java SQL date class. Java get current date time. Java convert calendar to date. Java compare dates. Java calculate elapsed time. Java convert date and time between timezone. Java add days to current date. Java variable arguments. Java string in switch case. Java try-with-resources. Java binary literals. Numeric literals with underscore. Java catch multiple exceptions.
0 notes
t-baba · 8 years ago
Photo
Tumblr media
Kotlin From Scratch: Ranges and Collections
Kotlin is a modern programming language that compiles to Java bytecode. It is free and open source, and promises to make coding for Android even more fun.
In the previous article in this series, you learned about nullability, loops, and conditions in Kotlin. In this tutorial, we'll continue to learn the language by looking at the ranges and collections API in Kotlin.
1. Ranges
A Range in Kotlin is a unique type that defines a start value and an end value. In other words, it is an interval between a start and an end value. Ranges in Kotlin are closed, meaning that the start value and end value are included in the range. 
We'll now look at the different ways of creating ranges in Kotlin.
The .. Operator
val oneToFive = 1..5
In the code above, we have created a closed range. This variable oneToFive will include the following values: 1, 2, 3, 4, 5. We can loop over it using the for loop construct.
for (n in oneToFive) { print(n) }
The code above can be shortened to:
for (n in 1..5) { print(n) }
We can also create a range of characters:
val aToZ = "a".."z"
The variable aToZ will have all the letters in the English alphabet.
The rangeTo() Function
The .. operator can be replaced with the rangeTo() extension function to create a range. For example, we can also do this 1.rangeTo(5) and it would still have the same results as using the .. operator as discussed earlier. 
val oneToFive: IntRange = 1.rangeTo(5)
The downTo() Function
This is another extension function that will create a range starting from a given number down to another one.
val fiveToOne = 5.downTo(1)
We can modify the range using the step() function. This will modify the delta between each element in the range.
val oneToTenStep = 1..10 step 2 // 1, 3, 5, 7, 9
The code above will contain odd numbers between 1 and 10.
The in Operator
The in operator is used to ascertain whether a value is present in a given range.
if (5 in 1..10) { print("Yes 5 is in the range") // prints "Yes 5 is in the range" }
In the code above, we checked to see if 5 is in the range 1..10 using the in operator. We can also do the opposite by using !n to check if 5 is not in the range.
2. Collections
Collections are used to store groups of related objects in memory. In a collection, we can retrieve, store or organize the objects. Kotlin provides its collections API as a standard library built on top of the Java Collections API. (We'll discuss interfaces in Kotlin in a future post.) 
You should note that these interfaces are linked to their implementation at compile time. You can't see the implementation source code in Kotlin, because the collections are actually implemented by the standard Java Collections such as ArrayList, Maps, HashMap, Sets, HashSet, List and so on. To really understand the collections API in Kotlin, you'll need to be familiar with these basic classes and interfaces in Java.
In this section, we'll learn about the List, Set and Map collections in Kotlin. (If you want a refresher on arrays in Kotlin, kindly visit the first tutorial in this series.) 
Kotlin's collections give us the ability to achieve a lot with just a little code—unlike in Java, which seems to need a lot of code to achieve a little! Kotlin has two variants of collections: mutable and immutable. A mutable collection provides us with the ability to modify a collection by either adding, removing or replacing an element. Immutable collections cannot be modified and don't have these helper methods. 
Note that the addition, removal or replacement of an element in an immutable collection is possible via operator functions (we'll get to that shortly), but these will end up creating a new collection.
The Iterable Interface
The Kotlin Iterable interface is at the top of the collections class hierarchy. This interface enables collections to be represented as a sequence of elements (which can be iterated over, naturally). 
public interface Iterable<out T> { public abstract operator fun iterator(): Iterator<T> }
The Collection Interface
The Kotlin Collection interface extends the Iterable interface. The Collection interface is immutable. In other words, you have read-only access to collections. The Set and List interfaces (more about these shortly) in Kotlin extend this interface. 
Some of the functions and properties available in the Collection interface are:
size: this property returns the size of the collection.
isEmpty(): returns true if the collection is empty or false otherwise. 
contains(element: E): returns true if the element specified in the argument is present in the collection.
containsAll(element: Collection<E>): returns true if the element in the collection passed as argument is present in the collection.  
public interface Collection<out E> : Iterable<E> { public val size: Int public fun isEmpty(): Boolean public operator fun contains(element: @UnsafeVariance E): Boolean override fun iterator(): Iterator<E> public fun containsAll(elements: Collection<@UnsafeVariance E>): Boolean }
The MutableIterable Interface
This interface in Kotlin gives us a specialized mutable iterator from the parent Iterable interface.
public interface MutableIterable<out T> : Iterable<T> { override fun iterator(): MutableIterator<T> }
The MutableCollection Interface
The MutableCollection interface in Kotlin is a specialized interface that enables collections to be mutable. In other words, add and remove operations can be performed on a given collection. This interface extends both the Collection interface and the MutableIterable interface already discussed above. The MutableSet and MutableList interfaces (we'll get to them shortly) in Kotlin extend this interface. The functions available in this interface—apart from the ones available in its parents—are:
add(element: E): adds the element passed as an argument to the collection and returns true if successful or false if the collection does not support duplicates and the element is already present.
remove(element: E): removes the element passed as an argument from the collection. Returns true if successful or false if it was not present in the collection.
addAll(elements: Collection<E>): adds all the elements in the collection passed as arguments to the collection. Returns true if successful or false if nothing was added.
removeAll(elements: Collection<E>): removes all of the elements present in the collection passed as arguments. Returns true if successful or false if nothing was removed.
retainAll(elements: Collection<E>): retains only the elements present in the collections passed as arguments. Returns true if successful or false if nothing was retained. 
clear(): removes all elements from this collection.
public interface MutableCollection<E> : Collection<E>, MutableIterable<E> { override fun iterator(): MutableIterator<E> public fun add(element: E): Boolean public fun remove(element: E): Boolean public fun addAll(elements: Collection<E>): Boolean public fun removeAll(elements: Collection<E>): Boolean public fun retainAll(elements: Collection<E>): Boolean public fun clear(): Unit }
Now you have learned about the top interfaces in the collection class hierarchy in Kotlin, let's now look into how Kotlin handles collections such as Lists, Sets and Maps in the remaining part of the tutorial.
Lists
A list is an ordered collection of elements. This is a popular collection that is widely used. Let's look at different ways of creating a list in Kotlin.
Using the listOf() Function
In Kotlin, we can create an immutable (read-only) list using the listOf() helper function from the Kotlin standard library. This function returns a Kotlin List interface type.
var numbers: List<Int> = listOf(1, 2, 3, 4, 5) var names: List<String> = listOf("Chike", "Nnamdi", "Mgbemena") for (name in names) { println(name) }
Running the code above will print: 
Chike Nnamdi Mgbemena
Moreover, we can pass values of different types into the listOf() as arguments and the result will still work—it will be a list of mixed type. 
var listMixedTypes = listOf("Chike", 1, 2.445, 's') // will still compile
Using the emptyList() Function
This function just creates an empty immutable list and returns a Kotlin List interface type.
val emptyList: List<String> = emptyList<String>()
Using the listOfNotNull() Function
This function creates a new immutable list containing only elements that are not null. Notice that this function returns a Kotlin List interface type also.
val nonNullsList: List<String> = listOfNotNull(2, 45, 2, null, 5, null)
The List interface from the Kotlin standard library extends only the Collection interface. In other words, its only parent is the Collection interface. It overrides all the functions in the parent interface to cater for its special needs and also defines its own functions, such as:
get(index: Int): a function operator that returns the element at the specified index. 
indexOf(element: E): returns the index of the first occurrence of the element passed as an argument in the list, or -1 if none is found.
lastIndexOf(element: E): returns the index of the last occurrence of the element passed as an argument in the list, or -1 if none is found. 
listIterator(): returns a list iterator over the elements in the list.
subList(fromIndex: Int, toIndex: Int): returns a list that contains the portion of the list between the specified start and end indices. 
println(names.size) // 3 println(names.get(0)) // "Chike" println(names.indexOf("Mgbemena")) // 2 println(names.contains("Nnamdi")) // 'true'
Using the arrayListOf() Function
This creates a mutable list and returns a Java ArrayList type.
val stringList: ArrayList<String> = arrayListOf<String>("Hello", "You", "There")
Using the mutableListOf() Function
To add, remove or replace values in a list, we need to make the list a mutable one. We can convert an immutable list to a mutable one by calling the function toMutableList() on the list. However, note that this method will create a new list.
var mutableNames1 = names.toMutableList() mutableNames1.add("Ruth") // now mutable and added "Ruth" to list
To create a mutable list of a certain type from scratch, e.g. String, we use mutableListOf<String>(), while for mixed types we can just use the mutableListOf() function instead.
// a mutable list of a certain type e.g. String val mutableListNames: MutableList<String> = mutableListOf<String>("Josh", "Kene", "Sanya") mutableListNames.add("Mary") mutableListNames.removeAt(1) mutableListNames[0] = "Oluchi" // replaces the element in index 0 with "Oluchi" // a mutable list of mixed types val mutableListMixed = mutableListOf("BMW", "Toyota", 1, 6.76, 'v')
Any of these functions will return a MutableList Kotlin interface type. This interface extends both the MutableCollection and List interfaces discussed earlier in this section. The MutableList interface adds methods for the retrieval or substitution of an item based upon its position: 
set(index: Int, element: E): substitutes an element in the list with another element. This returns the element previously at the specified position.
add(index: Int, element: E): inserts an element at the specified index. 
removeAt(index: Int): gets rid of the element at a particular index. 
val mutableListFood: MutableList<String> = mutableListOf<String>("Rice & stew", "Jollof rice", "Eba & Egusi", "Fried rice") mutableListFood.remove("Fried rice") mutableListFood.removeAt(0) mutableListFood.set(0, "Beans") mutableListFood.add(1, "Bread & tea") for (foodName in mutableListFood) { println(foodName) }
Running the code above, we produce the following result:
Beans Bread & tea Eba & Egusi
Note that all these functions create a Java ArrayList behind the scenes.
Sets
A set is an unordered collection of unique elements. In other words, it can't have any duplicates! Let's look at some of the different ways of creating a set in Kotlin. Each of these creates a different data structure, each of which is optimized for a certain kind of task. 
Using the setOf() Function
To create an immutable (read-only) set in Kotlin, we can use the function setOf(), which returns a Kotlin Set interface type. 
// creates a immutable set of mixed types val mixedTypesSet = setOf(2, 4.454, "how", "far", 'c') // will compile var intSet: Set<Int> = setOf(1, 3, 4) // only integers types allowed
Note that the Kotlin Set interface extends only the Kotlin Collection interface and overrides all the properties available in its parent.
Using the hashSetOf() Function 
Using the hashSetOf() function creates a Java HashSet collection which stores elements in a hash table. Because this function returns a Java HashSet type, we can add, remove, or clear elements in the set. In other words, it's mutable. 
val intsHashSet: java.util.HashSet<Int> = hashSetOf(1, 2, 6, 3) intsHashSet.add(5) intsHashSet.remove(1)
Using the sortedSetOf() Function
Using the sortedSetOf() function creates a Java TreeSet collection behind the scenes, which orders elements based on their natural ordering or by a comparator. This set is also mutable.
val intsSortedSet: java.util.TreeSet<Int> = sortedSetOf(4, 1, 7, 2) intsSortedSet.add(6) intsSortedSet.remove(1) intsSortedSet.clear()
Using the linkedSetOf() Function
This function returns a Java LinkedHashSet type. This mutable set maintains a linked list of the entries in the set, in the order in which they were inserted. 
val intsLinkedHashSet: java.util.LinkedHashSet<Int> = linkedSetOf(5, 2, 7, 2, 5) // 5, 2, 7 intsLinkedHashSet.add(4) intsLinkedHashSet.remove(2) intsLinkedHashSet.clear()
Using the mutableSetOf() Function
We can use mutableSetOf() to create a mutable set. This function returns a Kotlin MutableSet interface type. Behind the scenes, this function simply creates a Java LinkedHashSet.  
// creates a mutable set of int types only val intsMutableSet: MutableSet<Int> = mutableSetOf(3, 5, 6, 2, 0) intsMutableSet.add(8) intsMutableSet.remove(3)
The MutableSet interface extends both the MutableCollection and the Set interfaces. 
Maps
Maps associate keys to values. The keys must be unique, but the associated values don't need to be. That way, each key can be used to uniquely identify the associated value, since the map makes sure that you can't have duplicate keys in the collection. Behind the scenes, Kotlin uses the Java Map collection to implement its map collection type.
Using the mapOf() Function
To create an immutable or read-only Map collection in Kotlin, we use the mapOf() function. We create a map with this function by giving it a list of pairs—the first value is the key, and the second is the value. Calling this function returns a Kotlin Map interface type.
val callingCodesMap: Map<Int, String> = mapOf(234 to "Nigeria", 1 to "USA", 233 to "Ghana") for ((key, value) in callingCodesMap) { println("$key is the calling code for $value") } print(callingCodesMap[234]) // Nigeria
Running the code above will produce the result: 
234 is the calling code for Nigeria 1 is the calling code for USA 233 is the calling code for Ghana
Unlike the List and Set interfaces in Kotlin that extend the Collection interface, the Map interface doesn't extend any at all. Some of the properties and functions available in this interface are:
size: this property returns the size of map collection.
isEmpty(): returns true if the map is empty or false otherwise.
containsKey(key: K): returns true if the map contains the key in the argument. 
containsValue(value: V): returns true if the map maps one or more keys to the value passed as an argument.
get(key: K): returns the value matching the given key or 'null' if none is found. 
keys: this property returns an immutable Set of all the keys in the map.
values: returns an immutable Collection of all the values in the map.
Using the mutableMapOf() Function
The mutableMapOf() function creates a mutable map for us so that we can add and remove elements in the map. This returns a Kotlin MutableMap interface type.
val currenciesMutableMap: MutableMap<String, String> = mutableMapOf("Naira" to "Nigeria", "Dollars" to "USA", "Pounds" to "UK") println("Countries are ${currenciesMutableMap.values}") // Countries are [Nigeria, USA, UK] println("Currencies are ${currenciesMutableMap.keys}") // Currencies are [Naira, Dollars, Pounds] currenciesMutableMap.put("Cedi", "Ghana") currenciesMutableMap.remove("Dollars")
The MutableMap interface doesn't extend the MutableCollection interface; it's only parent is the Map interface. It overrides the keys, entries and values properties from the parent interface in order to redefine them. Here are some of the extra functions available in the MutableMap interface:
put(key: K, value: V): inserts the key, value pair into the map. This will return the previous value linked with the key or null if the key was not previously used. 
remove(key: K): removes the key and its linked value from the map. 
putAll(from: Map<out K, V>): updates the map with all the data from the given map. New keys will be added, and existing keys will be updated with new values. 
clear(): removes all elements from the map. 
We can get the value for a key using the get() function. We can also use square bracket notation as a shortcut for get(). 
print(currenciesMutableMap.get("Nigeria")) // will print Naira print(currenciesMutableMap["Nigeria"]) // will print Naira
Using the hashMapOf() Function
Using this function returns a Java HashMap type that is mutable. The HashMap class uses a hash table to implement the Java Map interface.  
val personsHashMap: java.util.HashMap<Int, String> = hashMapOf(1 to "Chike", 2 to "John", 3 to "Emeka") personsHashMap.put(4, "Chuka") personsHashMap.remove(2) print(personsHashMap[1]) // will print Chike
Using the linkedHashMap() Function
This function returns a Java LinkedHashMap type that is mutable. The LinkedHashMap class extends Java HashMap and maintains a linked list of the entries in the map in the order in which they were inserted. 
val postalCodesHashMap: java.util.LinkedHashMap<String, String> = linkedMapOf("NG" to "Nigeria","AU" to "Australia","CA" to "Canada") postalCodesHashMap.put("NA", "Namibia") postalCodesHashMap.remove("AU") postalCodesHashMap.get("CA") // Canada
Using the sortedMapOf() Function
This function returns a Java SortedMap type which is mutable. The Java SortedMap class sees that the entries in the map are maintained in an ascending key order.
val personsSortedMap: java.util.SortedMap<Int, String> = sortedMapOf(2 to "Chike", 1 to "John", 3 to "Emeka") personsSortedMap.put(7, "Adam") personsSortedMap.remove(3)
Remember, implementation of these collection interfaces in Kotlin happens at compile time.
Collections Operation Functions
Kotlin provides us with many useful operator functions called extension functions that can be invoked on collections. Let's take a look at some of the most useful.
The last() Function
This operator function returns the last element in a collection such as a list or set. We can also supply a predicate to search within a subset of elements.
val stringList: List<String> = listOf("in", "the", "club") print(stringList.last()) // will print "club" // given a predicate print(stringList.last{ it.length == 3}) // will print "the" val intSet: Set<Int> = setOf(3, 5, 6, 6, 6, 3) print(intSet.last()) // will print 6
The first() Function
This operator function returns the first element when invoked on a collection such as a list or set. If a predicate is given, it then uses the predicate to restrict the operation to a subset of elements.
print(stringList.first()) // will print "in" print(intSet.first()) // will print 3
The max() Function
Invoking this operator function on a collection such as a list or set returns the largest element, or null if no largest element is found.
val intList: List<Int> = listOf(1, 3, 4) print(intList.max()) // will print 4 print(intSet.max()) // will print 6
The drop() Function
Calling this operator function returns a new list or set containing all elements except the first n elements.
print(stringList.drop(2)) // will print "club"
The plus() Function
This operator function returns a collection containing all elements of the original and then the given element if it isn't already in the collection. This will end up creating a new list instead of modifying the list.
print(intList.plus(6)) // will print [1, 3, 4, 6]
The minus() Function
The opposite of the plus() function is the minus() function. It returns a collection containing all elements of the original set except the given element. This also ends up creating a new list instead of altering the list.
print(intList.minus(3)) // will print [1, 4]
The average() Function
Calling this operator function will return an average number of elements in the collection.
print(intList.average()) // will print 2.6666666666666665
Most of these extension functions are available in the Kotlin collections standard library. You are advised to check out the documentation to learn about the others.
Conclusion
In this tutorial, you learned about the range and collections API in the Kotlin programming language. In the next tutorial in the Kotlin From Scratch series, you'll be introduced to functions in Kotlin. See you soon!
To learn more about the Kotlin language, I recommend visiting the Kotlin documentation. Or check out some of our other Android app development posts here on Envato Tuts!
Android SDK
Introduction to Android Architecture Components
Tin Megali
Machine Learning
Create Chatbots on Android With IBM Watson
Ashraff Hathibelagal
Android SDK
Java vs. Kotlin: Should You Be Using Kotlin for Android Development?
Jessica Thornsby
Android SDK
Quick Tip: Write Cleaner Code With Kotlin SAM Conversions
Ashraff Hathibelagal
Android SDK
Android O: Phone Number Verification With SMS Tokens
Chike Mgbemena
by Chike Mgbemena via Envato Tuts+ Code http://ift.tt/2xzRYTz
0 notes