Repository: goldmansachs/gs-collections-kata Branch: master Commit: a0282590141c Files: 39 Total size: 57.9 KB Directory structure: gitextract_6hnlp4sq/ ├── .classpath ├── .idea/ │ ├── copyright/ │ │ ├── Apache.xml │ │ └── profiles_settings.xml │ ├── libraries/ │ │ └── lib.xml │ ├── misc.xml │ ├── modules.xml │ └── runConfigurations/ │ └── All_in_GSCollectionsKata.xml ├── .project ├── .settings/ │ └── org.eclipse.jdt.core.prefs ├── GSCollectionsKata.iml ├── LICENSE-2.0.txt ├── NOTICE ├── README.md ├── lib/ │ ├── gs-collections-6.0.0.jar │ ├── gs-collections-api-6.0.0.jar │ ├── gs-collections-testutils-6.0.0.jar │ ├── hamcrest-core-1.3.jar │ ├── hamcrest-library-1.3.jar │ ├── junit-4.12.jar │ └── source/ │ ├── gs-collections-6.0.0-sources.jar │ ├── gs-collections-api-6.0.0-sources.jar │ ├── gs-collections-testutils-6.0.0-sources.jar │ ├── hamcrest-core-1.3-sources.jar │ ├── hamcrest-library-1.3-sources.jar │ └── junit-4.12-sources.jar └── src/ ├── main/ │ └── java/ │ └── com/ │ └── gs/ │ └── collections/ │ └── kata/ │ ├── Company.java │ ├── Customer.java │ ├── LineItem.java │ ├── Order.java │ └── Supplier.java └── test/ └── java/ └── com/ └── gs/ └── collections/ └── kata/ ├── CompanyDomainForKata.java ├── Exercise1Test.java ├── Exercise2Test.java ├── Exercise3Test.java ├── Exercise4Test.java ├── Exercise5Test.java ├── Exercise6Test.java ├── Exercise7Test.java └── Exercise8Test.java ================================================ FILE CONTENTS ================================================ ================================================ FILE: .classpath ================================================ ================================================ FILE: .idea/copyright/Apache.xml ================================================ ================================================ FILE: .idea/copyright/profiles_settings.xml ================================================ ================================================ FILE: .idea/libraries/lib.xml ================================================ ================================================ FILE: .idea/misc.xml ================================================ ================================================ FILE: .idea/modules.xml ================================================ ================================================ FILE: .idea/runConfigurations/All_in_GSCollectionsKata.xml ================================================ ================================================ FILE: .project ================================================ GS Collections Kata org.eclipse.jdt.core.javabuilder org.eclipse.jdt.core.javanature ================================================ FILE: .settings/org.eclipse.jdt.core.prefs ================================================ #Fri Dec 23 13:01:22 EST 2011 eclipse.preferences.version=1 org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve org.eclipse.jdt.core.compiler.compliance=1.6 org.eclipse.jdt.core.compiler.debug.lineNumber=generate org.eclipse.jdt.core.compiler.debug.localVariable=generate org.eclipse.jdt.core.compiler.debug.sourceFile=generate org.eclipse.jdt.core.compiler.problem.assertIdentifier=error org.eclipse.jdt.core.compiler.problem.enumIdentifier=error org.eclipse.jdt.core.compiler.source=1.6 ================================================ FILE: GSCollectionsKata.iml ================================================ ================================================ FILE: LICENSE-2.0.txt ================================================ Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ================================================ FILE: NOTICE ================================================ GS Collections Kata Copyright 2011 Goldman Sachs This product includes software (JUnit) developed by JUnit.org (http://www.junit.org/). ================================================ FILE: README.md ================================================ # GS Collections Kata ## What is a Code Kata? A _kata_ is an exercise in martial arts. A code kata is an exercise in programming which helps hone your skills through practice and repetition. You can find out more about code Katas in general [here](http://codekata.pragprog.com). ## What is the GS Collections Code Kata? The GS Collections Kata is a fun way to help you learn idiomatic GS Collections usage. This particular kata is set up as a series of unit tests which fail. Your task is to make them pass, using GS Collections. The Kata is meant to take approximately one eight-hour day. New concepts are introduced in the [slides](http://www.goldmansachs.com/gs-collections/documents/GS Collections Training Session and Kata 5.0.0.pdf), with coding exercises at the end of each section. As you complete each exercise, you can check your answers against the [solutions branch](https://github.com/goldmansachs/gs-collections-kata/tree/solutions). Make sure you read the instructor notes in the slides. In addition, you can refer to the [GS Collections Reference Guide](http://www.goldmansachs.com/gs-collections/documents/GS Collections Reference Guide 5.0.0.pdf) for further detail and examples of the API. ================================================ FILE: src/main/java/com/gs/collections/kata/Company.java ================================================ /* * Copyright 2015 Goldman Sachs. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.gs.collections.kata; import com.gs.collections.api.block.predicate.Predicate; import com.gs.collections.api.list.MutableList; import com.gs.collections.impl.list.mutable.FastList; import org.junit.Assert; /** * A company has a {@link MutableList} of {@link Customer}s. It has an array of {@link Supplier}s, and a name. */ public class Company { private final String name; private final MutableList customers = FastList.newList(); // suppliers are array based. private Supplier[] suppliers = new Supplier[0]; public Company(String name) { this.name = name; } public String getName() { return this.name; } public void addCustomer(Customer aCustomer) { this.customers.add(aCustomer); } public MutableList getCustomers() { return this.customers; } public MutableList getOrders() { Assert.fail("Refactor this code to use GS Collections as part of Exercise 3"); MutableList orders = FastList.newList(); for (Customer customer : this.customers) { orders.addAll(customer.getOrders()); } return orders; } public Customer getMostRecentCustomer() { return this.customers.getLast(); } public void addSupplier(Supplier supplier) { // need to replace the current array of suppliers with another, larger array // Of course, normally one would not use an array. final Supplier[] currentSuppliers = this.suppliers; this.suppliers = new Supplier[currentSuppliers.length + 1]; System.arraycopy(currentSuppliers, 0, this.suppliers, 0, currentSuppliers.length); this.suppliers[this.suppliers.length - 1] = supplier; } public Supplier[] getSuppliers() { return this.suppliers; } public Customer getCustomerNamed(String name) { /** * Use a {@link Predicate} to find a {@link Customer} with the name given. */ Assert.fail("Implement this method as part of Exercise 2"); return null; } } ================================================ FILE: src/main/java/com/gs/collections/kata/Customer.java ================================================ /* * Copyright 2015 Goldman Sachs. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.gs.collections.kata; import java.util.ArrayList; import java.util.List; import com.gs.collections.api.block.function.Function; import com.gs.collections.api.list.MutableList; import com.gs.collections.impl.block.function.AddFunction; import com.gs.collections.impl.utility.ListIterate; import org.junit.Assert; /** * Customers have a name, city and a list of {@link Order}s */ public class Customer { public static final Function TO_NAME = customer -> { Assert.fail("Replace with the implementation of the Function."); return null; }; public static final Function TO_CITY = null; public static final Function TO_TOTAL_ORDER_VALUE = Customer::getTotalOrderValue; private final String name; private final String city; private final List orders = new ArrayList<>(); public Customer(String name, String city) { this.name = name; this.city = city; } public String getCity() { return this.city; } public String getName() { return this.name; } public List getOrders() { return this.orders; } public void addOrder(Order anOrder) { this.orders.add(anOrder); } public double getTotalOrderValue() { MutableList orderValues = ListIterate.collect(this.orders, Order::getValue); return orderValues.injectInto(0.0, AddFunction.DOUBLE_TO_DOUBLE); } } ================================================ FILE: src/main/java/com/gs/collections/kata/LineItem.java ================================================ /* * Copyright 2015 Goldman Sachs. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.gs.collections.kata; import com.gs.collections.api.block.function.Function; /** * An Item has a name and a value. */ public class LineItem { public static final Function TO_NAME = LineItem::getName; private String name; private final double value; public String getName() { return this.name; } public void setName(String name) { this.name = name; } public double getValue() { return this.value; } public LineItem(String name, double value) { this.name = name; this.value = value; } @Override public String toString() { return this.name + " $ " + this.getValue(); } } ================================================ FILE: src/main/java/com/gs/collections/kata/Order.java ================================================ /* * Copyright 2015 Goldman Sachs. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.gs.collections.kata; import java.util.ArrayList; import java.util.Collection; import java.util.List; import com.gs.collections.api.block.function.Function; import com.gs.collections.impl.block.function.AddFunction; import com.gs.collections.impl.collection.mutable.CollectionAdapter; import com.gs.collections.impl.utility.Iterate; /** * Has a number, a {@link Customer}, a {@link List} of {@link LineItem}s, and a boolean that states whether or not the order * has been delivered. There is a class variable that contains the next order number. */ public class Order { public static final Function TO_VALUE = Order::getValue; public static final Function> TO_LINE_ITEMS = Order::getLineItems; private static int nextOrderNumber = 1; private final int orderNumber; private final List lineItems = new ArrayList<>(); private boolean isDelivered; public Order() { this.orderNumber = nextOrderNumber; nextOrderNumber += 1; } public static void resetNextOrderNumber() { nextOrderNumber = 1; } public void deliver() { this.isDelivered = true; } public boolean isDelivered() { return this.isDelivered; } public void addLineItem(LineItem aLineItem) { this.lineItems.add(aLineItem); } public List getLineItems() { return this.lineItems; } @Override public String toString() { return "order " + this.orderNumber + " items: " + this.lineItems.size(); } public double getValue() { Collection itemValues = Iterate.collect(this.lineItems, LineItem::getValue); return CollectionAdapter.adapt(itemValues).injectInto(0.0, AddFunction.DOUBLE_TO_DOUBLE); } } ================================================ FILE: src/main/java/com/gs/collections/kata/Supplier.java ================================================ /* * Copyright 2015 Goldman Sachs. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.gs.collections.kata; import com.gs.collections.api.block.function.Function; /** * Suppliers have a name and an array of itemNames. Suppliers don't like lists - they prefer arrays.... */ public class Supplier { public static final Function TO_NAME = Supplier::getName; public static final Function TO_NUMBER_OF_ITEMS = supplier -> supplier.getItemNames().length; private final String name; private final String[] itemNames; public Supplier(String name, String[] itemNames) { this.name = name; this.itemNames = itemNames; } public String getName() { return this.name; } public String[] getItemNames() { return this.itemNames; } } ================================================ FILE: src/test/java/com/gs/collections/kata/CompanyDomainForKata.java ================================================ /* * Copyright 2015 Goldman Sachs. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.gs.collections.kata; import org.junit.Before; public abstract class CompanyDomainForKata { protected final Company company = new Company("Bloggs Shed Supplies"); @Before public void setUp() { Order.resetNextOrderNumber(); this.setUpCustomersAndOrders(); this.setUpSuppliers(); } private void setUpSuppliers() { this.company.addSupplier(new Supplier("Shedtastic", new String[]{"shed", "big shed", "huge shed"})); this.company.addSupplier(new Supplier("Splendid Crocks", new String[]{"cup", "saucer", "bowl"})); this.company.addSupplier(new Supplier("Annoying Pets", new String[]{"dog", "cat", "goldfish"})); this.company.addSupplier(new Supplier("Gnomes 'R' Us", new String[]{"gnome"})); this.company.addSupplier(new Supplier("Furniture Hamlet", new String[]{"table", "sofa", "chair"})); this.company.addSupplier(new Supplier("SFD", new String[]{"sofa", "chair"})); this.company.addSupplier(new Supplier("Doxins", new String[]{"kettle", "plasma screen", "sandwich toaster"})); } private void setUpCustomersAndOrders() { Order fredOrder = new Order(); fredOrder.addLineItem(new LineItem("shed", 50.0)); /** * TODO 7: Refactor Order and its API so this repetition is not necessary. */ // TODO 7: Add 3 cups at 1.5 each to the order fredOrder.addLineItem(new LineItem("cup", 1.5)); fredOrder.addLineItem(new LineItem("cup", 1.5)); fredOrder.addLineItem(new LineItem("cup", 1.5)); // TODO 7: Add 3 saucers at 1.0 each to the order fredOrder.addLineItem(new LineItem("saucer", 1.0)); fredOrder.addLineItem(new LineItem("saucer", 1.0)); fredOrder.addLineItem(new LineItem("saucer", 1.0)); fredOrder.addLineItem(new LineItem("chair", 12.50)); fredOrder.addLineItem(new LineItem("table", 1.0)); Customer fred = new Customer("Fred", "London"); fred.addOrder(fredOrder); this.company.addCustomer(fred); Order maryOrder = new Order(); maryOrder.addLineItem(new LineItem("cat", 150.0)); maryOrder.addLineItem(new LineItem("big shed", 500.0)); // TODO 7: Add 4 cups at 1.50 each to the order maryOrder.addLineItem(new LineItem("cup", 1.5)); maryOrder.addLineItem(new LineItem("cup", 1.5)); maryOrder.addLineItem(new LineItem("cup", 1.5)); maryOrder.addLineItem(new LineItem("cup", 1.5)); // TODO 7: Add 4 saucers at 1.50 each to the order maryOrder.addLineItem(new LineItem("saucer", 1.5)); maryOrder.addLineItem(new LineItem("saucer", 1.5)); maryOrder.addLineItem(new LineItem("saucer", 1.5)); maryOrder.addLineItem(new LineItem("saucer", 1.5)); maryOrder.addLineItem(new LineItem("sofa", 120.0)); maryOrder.addLineItem(new LineItem("dog", 75.0)); Customer mary = new Customer("Mary", "Liphook"); mary.addOrder(maryOrder); this.company.addCustomer(mary); Order billOrder1 = new Order(); billOrder1.addLineItem(new LineItem("shed", 50.0)); // TODO 7: Add 43 gnomes at 7.50 each to the order for (int i = 0; i < 43; i++) { billOrder1.addLineItem(new LineItem("gnome", 7.50)); } Order billOrder2 = new Order(); billOrder2.addLineItem(new LineItem("bowl", 1.25)); billOrder2.addLineItem(new LineItem("goldfish", 0.50)); Order billOrder3 = new Order(); billOrder3.addLineItem(new LineItem("table", 1.0)); Customer bill = new Customer("Bill", "London"); bill.addOrder(billOrder1); bill.addOrder(billOrder2); bill.addOrder(billOrder3); this.company.addCustomer(bill); } } ================================================ FILE: src/test/java/com/gs/collections/kata/Exercise1Test.java ================================================ /* * Copyright 2015 Goldman Sachs. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.gs.collections.kata; import com.gs.collections.api.block.function.Function; import com.gs.collections.api.list.MutableList; import com.gs.collections.impl.list.mutable.FastList; import com.gs.collections.impl.test.Verify; import org.junit.Assert; import org.junit.Test; public class Exercise1Test extends CompanyDomainForKata { @Test public void getCustomerNames() { Function nameFunction = Customer::getName; /** * Get the name of each of the company's customers. */ MutableList customers = this.company.getCustomers(); MutableList customerNames = null; MutableList expectedNames = FastList.newListWith("Fred", "Mary", "Bill"); Assert.assertEquals(expectedNames, customerNames); } @Test public void getCustomerCities() { /** * Get the city for each of the company's customers. */ MutableList customers = this.company.getCustomers(); MutableList customerCities = null; MutableList expectedCities = FastList.newListWith("London", "Liphook", "London"); Assert.assertEquals(expectedCities, customerCities); } @Test public void getLondonCustomers() { /** * Which customers come from London? Get a collection of those which do. */ MutableList customers = this.company.getCustomers(); MutableList customersFromLondon = null; Verify.assertSize("Should be 2 London customers", 2, customersFromLondon); } } ================================================ FILE: src/test/java/com/gs/collections/kata/Exercise2Test.java ================================================ /* * Copyright 2015 Goldman Sachs. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.gs.collections.kata; import com.gs.collections.api.block.predicate.Predicate; import com.gs.collections.api.list.MutableList; import com.gs.collections.impl.test.Verify; import org.junit.Assert; import org.junit.Test; public class Exercise2Test extends CompanyDomainForKata { /** * Set up a {@link Predicate} that tests to see if a {@link Customer}'s city is "London" */ private static final Predicate CUSTOMER_FROM_LONDON = null; @Test public void customerFromLondonPredicate() { String predicateClass = CUSTOMER_FROM_LONDON.getClass().getSimpleName(); Assert.assertTrue( "Solution should use Predicates.attributeEquals() or a lambda but used " + predicateClass, "AttributePredicate".equals(predicateClass) || predicateClass.startsWith("Exercise2Test$$Lambda")); Customer customerFromLondon = new Customer("test customer", "London"); Assert.assertEquals( "Implement Customer.TO_CITY", "London", Customer.TO_CITY.valueOf(customerFromLondon)); Assert.assertTrue( "CUSTOMER_FROM_LONDON should accept Customers where city is London", CUSTOMER_FROM_LONDON.accept(customerFromLondon)); } /** * Do any customers come from London? Use the Predicate {@link #CUSTOMER_FROM_LONDON}. */ @Test public void doAnyCustomersLiveInLondon() { boolean anyCustomersFromLondon = false; Assert.assertTrue(anyCustomersFromLondon); } /** * Do all customers come from London? Use the Predicate {@link #CUSTOMER_FROM_LONDON}. */ @Test public void doAllCustomersLiveInLondon() { boolean allCustomersFromLondon = true; Assert.assertFalse(allCustomersFromLondon); } /** * How many customers come from London? Use the Predicate {@link #CUSTOMER_FROM_LONDON}. */ @Test public void howManyCustomersLiveInLondon() { int numberOfCustomerFromLondon = 0; Assert.assertEquals("Should be 2 London customers", 2, numberOfCustomerFromLondon); } /** * Which customers come from London? Get a collection of those which do. Use the Predicate {@link * #CUSTOMER_FROM_LONDON}. */ @Test public void getLondonCustomers() { MutableList customersFromLondon = null; Verify.assertSize("Should be 2 London customers", 2, customersFromLondon); } /** * Which customers do not come from London? Get a collection of those which don't. Use the Predicate {@link * #CUSTOMER_FROM_LONDON}. */ @Test public void getCustomersWhoDontLiveInLondon() { MutableList customersNotFromLondon = null; Verify.assertSize("customers not from London", 1, customersNotFromLondon); } /** * Which customers come from London? Which customers do not come from London? Get a collection of each in a single pass. * Use the Predicate {@link #CUSTOMER_FROM_LONDON}. */ @Test public void getCustomersWhoDoAndDoNotLiveInLondon() { MutableList customersFromLondon = null; MutableList customersNotFromLondon = null; Verify.assertSize("Should be 2 London customers", 2, customersFromLondon); Verify.assertSize("customers not from London", 1, customersNotFromLondon); } /** * Implement {@link Company#getCustomerNamed(String)} and get this test to pass. */ @Test public void findMary() { Customer mary = this.company.getCustomerNamed("Mary"); Assert.assertEquals("customer's name should be Mary", "Mary", mary.getName()); } /** * Implement {@link Company#getCustomerNamed(String)} and get this test to pass. */ @Test public void findPete() { Customer pete = this.company.getCustomerNamed("Pete"); Assert.assertNull( "Should be null as there is no customer called Pete", pete); } } ================================================ FILE: src/test/java/com/gs/collections/kata/Exercise3Test.java ================================================ /* * Copyright 2015 Goldman Sachs. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.gs.collections.kata; import com.gs.collections.api.list.MutableList; import com.gs.collections.api.set.MutableSet; import com.gs.collections.impl.list.mutable.FastList; import com.gs.collections.impl.set.mutable.UnifiedSet; import com.gs.collections.impl.test.Verify; import org.junit.Assert; import org.junit.Test; public class Exercise3Test extends CompanyDomainForKata { /** * Improve {@link Company#getOrders()} without breaking this test. */ @Test public void improveGetOrders() { // Delete this line - it's a reminder Assert.fail("Improve getOrders() without breaking this test"); Verify.assertSize(5, this.company.getOrders()); } /** * Get all items that have been ordered by anybody. */ @Test public void findItemNames() { MutableList allOrderedLineItems = null; MutableSet actualItemNames = null; Verify.assertInstanceOf(MutableSet.class, actualItemNames); Verify.assertInstanceOf(String.class, actualItemNames.getFirst()); MutableSet expectedItemNames = UnifiedSet.newSetWith( "shed", "big shed", "bowl", "cat", "cup", "chair", "dog", "goldfish", "gnome", "saucer", "sofa", "table"); Assert.assertEquals(expectedItemNames, actualItemNames); } @Test public void findCustomerNames() { MutableList names = null; MutableList expectedNames = FastList.newListWith("Fred", "Mary", "Bill"); Assert.assertEquals(expectedNames, names); } } ================================================ FILE: src/test/java/com/gs/collections/kata/Exercise4Test.java ================================================ /* * Copyright 2015 Goldman Sachs. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.gs.collections.kata; import java.util.List; import com.gs.collections.api.block.predicate.Predicate; import com.gs.collections.api.list.MutableList; import com.gs.collections.impl.list.mutable.FastList; import com.gs.collections.impl.utility.ArrayIterate; import com.gs.collections.impl.utility.Iterate; import org.junit.Assert; import org.junit.Test; public class Exercise4Test extends CompanyDomainForKata { /** * Solve this without changing the return type of {@link Company#getSuppliers()}. Find the appropriate method on * {@link ArrayIterate}. */ @Test public void findSupplierNames() { MutableList supplierNames = null; MutableList expectedSupplierNames = FastList.newListWith( "Shedtastic", "Splendid Crocks", "Annoying Pets", "Gnomes 'R' Us", "Furniture Hamlet", "SFD", "Doxins"); Assert.assertEquals(expectedSupplierNames, supplierNames); } /** * Create a {@link Predicate} for Suppliers that supply more than 2 items. Find the number of suppliers that * satisfy that Predicate. */ @Test public void countSuppliersWithMoreThanTwoItems() { Predicate moreThanTwoItems = null; int suppliersWithMoreThanTwoItems = 0; Assert.assertEquals("suppliers with more than 2 items", 5, suppliersWithMoreThanTwoItems); } /** * Try to solve this without changing the return type of {@link Supplier#getItemNames()}. */ @Test public void whoSuppliesSandwichToaster() { // Create a Predicate that will check to see if a Supplier supplies a "sandwich toaster". Predicate suppliesToaster = null; // Find one supplier that supplies toasters. Supplier toasterSupplier = null; Assert.assertNotNull("toaster supplier", toasterSupplier); Assert.assertEquals("Doxins", toasterSupplier.getName()); } @Test public void filterOrderValues() { List orders = this.company.getMostRecentCustomer().getOrders(); /** * Get the order values that are greater than 1.5. */ MutableList orderValues = null; MutableList filtered = null; Assert.assertEquals(FastList.newListWith(372.5, 1.75), filtered); } @Test public void filterOrders() { List orders = this.company.getMostRecentCustomer().getOrders(); /** * Get the actual orders (not their double values) where those orders have a value greater than 2.0. */ MutableList filtered = null; Assert.assertEquals(FastList.newListWith(Iterate.getFirst(this.company.getMostRecentCustomer().getOrders())), filtered); } } ================================================ FILE: src/test/java/com/gs/collections/kata/Exercise5Test.java ================================================ /* * Copyright 2015 Goldman Sachs. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.gs.collections.kata; import java.util.List; import com.gs.collections.api.list.MutableList; import com.gs.collections.impl.block.factory.Predicates; import com.gs.collections.impl.list.mutable.FastList; import com.gs.collections.impl.test.Verify; import com.gs.collections.impl.utility.Iterate; import org.junit.Assert; import org.junit.Test; public class Exercise5Test extends CompanyDomainForKata { @Test public void filterOrderValues() { List orders = this.company.getMostRecentCustomer().getOrders(); /** * Same exercise but don't use static utility - refactor the type of orders and {@link Customer#getOrders()} * instead. * Get the order values that are greater than 1.5. */ MutableList orderValues = null; MutableList filtered = orderValues.select(Predicates.greaterThan(1.5)); Assert.assertEquals(FastList.newListWith(372.5, 1.75), filtered); Verify.assertInstanceOf(MutableList.class, this.company.getMostRecentCustomer().getOrders()); this.company.getMostRecentCustomer().getOrders().add(null); Verify.assertContains("Don't return a copy from Customer.getOrders(). The field should be a MutableList.", null, this.company.getMostRecentCustomer().getOrders()); } @Test public void filterOrders() { List orders = this.company.getMostRecentCustomer().getOrders(); /** * Same exercise but don't use static utility - refactor the type of orders and {@link Customer#getOrders()} * instead. * Get the actual orders (not their double values) where those orders have a value greater than 2.0. */ MutableList filtered = null; Assert.assertEquals(FastList.newListWith(Iterate.getFirst(this.company.getMostRecentCustomer().getOrders())), filtered); Verify.assertInstanceOf(MutableList.class, this.company.getMostRecentCustomer().getOrders()); this.company.getMostRecentCustomer().getOrders().add(null); Verify.assertContains("Don't return a copy from Customer.getOrders(). The field should be a MutableList.", null, this.company.getMostRecentCustomer().getOrders()); } } ================================================ FILE: src/test/java/com/gs/collections/kata/Exercise6Test.java ================================================ /* * Copyright 2015 Goldman Sachs. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.gs.collections.kata; import com.gs.collections.api.RichIterable; import com.gs.collections.api.block.procedure.Procedure; import com.gs.collections.api.list.MutableList; import com.gs.collections.impl.block.factory.Procedures; import com.gs.collections.impl.test.Verify; import org.junit.Assert; import org.junit.Test; public class Exercise6Test extends CompanyDomainForKata { /** * Get a list of the customers' total order values, sorted. Check out the implementation of {@link * Customer#getTotalOrderValue()} and {@link Order#getValue()} . */ @Test public void sortedTotalOrderValue() { MutableList sortedTotalValues = null; // Don't forget the handy utility methods getFirst() and getLast()... Assert.assertEquals("Highest total order value", Double.valueOf(857.0), sortedTotalValues.getLast()); Assert.assertEquals("Lowest total order value", Double.valueOf(71.0), sortedTotalValues.getFirst()); } /** * Find the max total order value across all customers. */ @Test public void maximumTotalOrderValue() { Double maximumTotalOrderValue = null; Assert.assertEquals("max value", Double.valueOf(857.0), maximumTotalOrderValue); } /** * Find the customer with the highest total order value. */ @Test public void customerWithMaxTotalOrderValue() { Customer customerWithMaxTotalOrderValue = null; Assert.assertEquals(this.company.getCustomerNamed("Mary"), customerWithMaxTotalOrderValue); } /** * Create some code to get the company's supplier names as a tilde delimited string. */ @Test public void supplierNamesAsTildeDelimitedString() { String tildeSeparatedNames = null; Assert.assertEquals( "tilde separated names", "Shedtastic~Splendid Crocks~Annoying Pets~Gnomes 'R' Us~Furniture Hamlet~SFD~Doxins", tildeSeparatedNames); } /** * Deliver all orders going to customers from London. *

* Hint: Use {@link RichIterable#forEach(Procedure)}. To solve the ambiguity error, use {@link Procedures#cast(Procedure)}}. * * @see Order#deliver() */ @Test public void deliverOrdersToLondon() { Verify.assertAllSatisfy(this.company.getCustomerNamed("Fred").getOrders(), Order::isDelivered); Verify.assertNoneSatisfy(this.company.getCustomerNamed("Mary").getOrders(), Order::isDelivered); Verify.assertAllSatisfy(this.company.getCustomerNamed("Bill").getOrders(), Order::isDelivered); } } ================================================ FILE: src/test/java/com/gs/collections/kata/Exercise7Test.java ================================================ /* * Copyright 2015 Goldman Sachs. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.gs.collections.kata; import java.util.List; import com.gs.collections.api.map.MutableMap; import com.gs.collections.api.multimap.list.MutableListMultimap; import com.gs.collections.impl.list.mutable.FastList; import com.gs.collections.impl.map.mutable.UnifiedMap; import com.gs.collections.impl.test.Verify; import org.junit.Assert; import org.junit.Test; public class Exercise7Test extends CompanyDomainForKata { /** * Create a multimap where the keys are the names of cities and the values are the customers from those cities. */ @Test public void customersByCity() { // Notice that the second generic type is Customer, not List MutableListMultimap multimap = null; Assert.assertEquals(FastList.newListWith(this.company.getCustomerNamed("Mary")), multimap.get("Liphook")); Assert.assertEquals( FastList.newListWith( this.company.getCustomerNamed("Fred"), this.company.getCustomerNamed("Bill")), multimap.get("London")); } @Test public void mapOfItemsToSuppliers() { Assert.fail("Refactor this as part of Exercise 7"); /** * Change itemsToSuppliers to a MutableMultimap */ final MutableMap> itemsToSuppliers = UnifiedMap.newMap(); for (Supplier supplier : this.company.getSuppliers()) { for (String itemName : supplier.getItemNames()) { List suppliersForItem; if (itemsToSuppliers.containsKey(itemName)) { suppliersForItem = itemsToSuppliers.get(itemName); } else { suppliersForItem = FastList.newList(); itemsToSuppliers.put(itemName, suppliersForItem); } suppliersForItem.add(supplier); } } Verify.assertIterableSize("should be 2 suppliers for sofa", 2, itemsToSuppliers.get("sofa")); } @Test public void reminder() { Assert.fail("Refactor setUpCustomersAndOrders() in the super class to not have so much repetition."); // Delete this whole method when you're done. It's just a reminder. } } ================================================ FILE: src/test/java/com/gs/collections/kata/Exercise8Test.java ================================================ /* * Copyright 2015 Goldman Sachs. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.gs.collections.kata; import java.util.Collections; import com.gs.collections.api.RichIterable; import com.gs.collections.api.bag.sorted.MutableSortedBag; import com.gs.collections.api.block.function.Function; import com.gs.collections.api.block.function.Function0; import com.gs.collections.api.block.function.Function2; import com.gs.collections.api.list.MutableList; import com.gs.collections.api.map.MutableMap; import com.gs.collections.api.multimap.list.MutableListMultimap; import com.gs.collections.impl.bag.sorted.mutable.TreeBag; import com.gs.collections.impl.list.mutable.FastList; import com.gs.collections.impl.test.Verify; import org.junit.Assert; import org.junit.Test; public class Exercise8Test extends CompanyDomainForKata { /** * Extra credit. Aggregate the total order values by city. * * @see RichIterable#aggregateBy(Function, Function0, Function2) */ @Test public void totalOrderValuesByCity() { Function0 zeroValueFactory = () -> 0.0; Function2 aggregator = (result, customer) -> result + customer.getTotalOrderValue(); MutableMap map = null; Assert.assertEquals(2, map.size()); Assert.assertEquals(446.25, map.get("London"), 0.0); Assert.assertEquals(857.0, map.get("Liphook"), 0.0); } /** * Extra credit. Aggregate the total order values by item. * Hint: Look at {@link RichIterable#aggregateBy(Function, Function0, Function2)} and remember * how to use {@link RichIterable#flatCollect(Function)} to get an iterable of all items. */ @Test public void totalOrderValuesByItem() { Function0 zeroValueFactory = () -> 0.0; Function2 aggregator = (result, lineItem) -> result + lineItem.getValue(); MutableMap map = null; Verify.assertSize(12, map); Assert.assertEquals(100.0, map.get("shed"), 0.0); Assert.assertEquals(10.5, map.get("cup"), 0.0); } /** * Extra credit. Find all customers' line item values greater than 7.5 and sort them by highest to lowest price. */ @Test public void sortedOrders() { MutableSortedBag orderedPrices = null; MutableSortedBag expectedPrices = TreeBag.newBagWith( Collections.reverseOrder(), 500.0, 150.0, 120.0, 75.0, 50.0, 50.0, 12.5); Verify.assertSortedBagsEqual(expectedPrices, orderedPrices); } /** * Extra credit. Figure out which customers ordered saucers (in any of their orders). */ @Test public void whoOrderedSaucers() { MutableList customersWithSaucers = null; Verify.assertSize("customers with saucers", 2, customersWithSaucers); } /** * Extra credit. Look into the {@link MutableList#toMap(Function, Function)} method. */ @Test public void ordersByCustomerUsingAsMap() { MutableMap> customerNameToOrders = this.company.getCustomers().toMap(null, null); Assert.assertNotNull("customer name to orders", customerNameToOrders); Verify.assertSize("customer names", 3, customerNameToOrders); MutableList ordersForBill = customerNameToOrders.get("Bill"); Verify.assertSize("Bill orders", 3, ordersForBill); } /** * Extra credit. Create a multimap where the values are customers and the key is the price of * the most expensive item that the customer ordered. */ @Test public void mostExpensiveItem() { MutableListMultimap multimap = null; Assert.assertEquals(3, multimap.size()); Assert.assertEquals(2, multimap.keysView().size()); Assert.assertEquals( FastList.newListWith( this.company.getCustomerNamed("Fred"), this.company.getCustomerNamed("Bill")), multimap.get(50.0)); } }