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
================================================
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="src/main/java"/>
<classpathentry kind="src" path="src/test/java"/>
<classpathentry kind="lib" path="lib/junit-4.10.jar" sourcepath="lib/source/junit-4.10-sources.jar"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
<classpathentry kind="lib" path="lib/collections-1.2.0.jar" sourcepath="lib/source/collections-1.2.0-sources.jar"/>
<classpathentry kind="lib" path="lib/collections-api-1.2.0.jar" sourcepath="lib/source/collections-api-1.2.0-sources.jar"/>
<classpathentry kind="lib" path="lib/collections-testutils-1.2.0.jar" sourcepath="lib/source/collections-testutils-1.2.0-sources.jar"/>
<classpathentry kind="output" path="target"/>
</classpath>
================================================
FILE: .idea/copyright/Apache.xml
================================================
<component name="CopyrightManager">
<copyright>
<option name="notice" value="Copyright &#36;today.year 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." />
<option name="keyword" value="Copyright" />
<option name="allowReplaceKeyword" value="" />
<option name="myName" value="Apache" />
<option name="myLocal" value="true" />
</copyright>
</component>
================================================
FILE: .idea/copyright/profiles_settings.xml
================================================
<component name="CopyrightManager">
<settings default="Apache">
<module2copyright />
<LanguageOptions name="XML">
<option name="fileLocation" value="2" />
</LanguageOptions>
</settings>
</component>
================================================
FILE: .idea/libraries/lib.xml
================================================
<component name="libraryTable">
<library name="lib">
<CLASSES>
<root url="file://$PROJECT_DIR$/lib" />
</CLASSES>
<JAVADOC />
<SOURCES>
<root url="file://$PROJECT_DIR$/lib/source" />
</SOURCES>
<jarDirectory url="file://$PROJECT_DIR$/lib" recursive="false" />
<jarDirectory url="file://$PROJECT_DIR$/lib/source" recursive="false" type="SOURCES" />
</library>
</component>
================================================
FILE: .idea/misc.xml
================================================
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="EntryPointsManager">
<entry_points version="2.0" />
</component>
<component name="ProjectRootManager" version="2" languageLevel="JDK_1_8" assert-keyword="true" jdk-15="true" project-jdk-name="1.8" project-jdk-type="JavaSDK" />
</project>
================================================
FILE: .idea/modules.xml
================================================
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/GSCollectionsKata.iml" filepath="$PROJECT_DIR$/GSCollectionsKata.iml" />
</modules>
</component>
</project>
================================================
FILE: .idea/runConfigurations/All_in_GSCollectionsKata.xml
================================================
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="All in GSCollectionsKata" type="JUnit" factoryName="JUnit">
<extension name="coverage" enabled="false" merge="false" sample_coverage="true" runner="idea" />
<module name="GSCollectionsKata" />
<option name="ALTERNATIVE_JRE_PATH_ENABLED" value="false" />
<option name="ALTERNATIVE_JRE_PATH" value="" />
<option name="PACKAGE_NAME" value="" />
<option name="MAIN_CLASS_NAME" value="" />
<option name="METHOD_NAME" value="" />
<option name="TEST_OBJECT" value="package" />
<option name="VM_PARAMETERS" value="" />
<option name="PARAMETERS" value="" />
<option name="WORKING_DIRECTORY" value="file://$PROJECT_DIR$" />
<option name="ENV_VARIABLES" />
<option name="PASS_PARENT_ENVS" value="true" />
<option name="TEST_SEARCH_SCOPE">
<value defaultName="moduleWithDependencies" />
</option>
<envs />
<patterns />
<RunnerSettings RunnerId="Run" />
<ConfigurationWrapper RunnerId="Run" />
<method />
</configuration>
</component>
================================================
FILE: .project
================================================
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>GS Collections Kata</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>
================================================
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
================================================
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="false">
<output url="file://$MODULE_DIR$/target" />
<output-test url="file://$MODULE_DIR$/target" />
<exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src/main/java" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/src/test/java" isTestSource="true" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" name="lib" level="project" />
</component>
</module>
================================================
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<Customer> 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<Customer> getCustomers()
{
return this.customers;
}
public MutableList<Order> getOrders()
{
Assert.fail("Refactor this code to use GS Collections as part of Exercise 3");
MutableList<Order> 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<Customer, String> TO_NAME = customer -> {
Assert.fail("Replace with the implementation of the Function.");
return null;
};
public static final Function<Customer, String> TO_CITY = null;
public static final Function<Customer, Double> TO_TOTAL_ORDER_VALUE = Customer::getTotalOrderValue;
private final String name;
private final String city;
private final List<Order> 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<Order> getOrders()
{
return this.orders;
}
public void addOrder(Order anOrder)
{
this.orders.add(anOrder);
}
public double getTotalOrderValue()
{
MutableList<Double> 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<LineItem, String> 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<Order, Double> TO_VALUE = Order::getValue;
public static final Function<Order, Iterable<LineItem>> TO_LINE_ITEMS = Order::getLineItems;
private static int nextOrderNumber = 1;
private final int orderNumber;
private final List<LineItem> 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<LineItem> getLineItems()
{
return this.lineItems;
}
@Override
public String toString()
{
return "order " + this.orderNumber + " items: " + this.lineItems.size();
}
public double getValue()
{
Collection<Double> 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<Supplier, String> TO_NAME = Supplier::getName;
public static final Function<Supplier, Integer> 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<Customer, String> nameFunction = Customer::getName;
/**
* Get the name of each of the company's customers.
*/
MutableList<Customer> customers = this.company.getCustomers();
MutableList<String> customerNames = null;
MutableList<String> 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<Customer> customers = this.company.getCustomers();
MutableList<String> customerCities = null;
MutableList<String> 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<Customer> customers = this.company.getCustomers();
MutableList<Customer> 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> 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<Customer> 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<Customer> 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<Customer> customersFromLondon = null;
MutableList<Customer> 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<LineItem> allOrderedLineItems = null;
MutableSet<String> actualItemNames = null;
Verify.assertInstanceOf(MutableSet.class, actualItemNames);
Verify.assertInstanceOf(String.class, actualItemNames.getFirst());
MutableSet<String> 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<String> names = null;
MutableList<String> 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<String> supplierNames = null;
MutableList<String> 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<Supplier> 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<Supplier> 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<Order> orders = this.company.getMostRecentCustomer().getOrders();
/**
* Get the order values that are greater than 1.5.
*/
MutableList<Double> orderValues = null;
MutableList<Double> filtered = null;
Assert.assertEquals(FastList.newListWith(372.5, 1.75), filtered);
}
@Test
public void filterOrders()
{
List<Order> orders = this.company.getMostRecentCustomer().getOrders();
/**
* Get the actual orders (not their double values) where those orders have a value greater than 2.0.
*/
MutableList<Order> 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<Order> 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<Double> orderValues = null;
MutableList<Double> 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<Order> 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<Order> 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<Double> 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.
* <p>
* 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<Customer>
MutableListMultimap<String, Customer> 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<String, Supplier>
*/
final MutableMap<String, List<Supplier>> itemsToSuppliers = UnifiedMap.newMap();
for (Supplier supplier : this.company.getSuppliers())
{
for (String itemName : supplier.getItemNames())
{
List<Supplier> 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<Double> zeroValueFactory = () -> 0.0;
Function2<Double, Customer, Double> aggregator = (result, customer) -> result + customer.getTotalOrderValue();
MutableMap<String, Double> 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<Double> zeroValueFactory = () -> 0.0;
Function2<Double, LineItem, Double> aggregator = (result, lineItem) -> result + lineItem.getValue();
MutableMap<String, Double> 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<Double> orderedPrices = null;
MutableSortedBag<Double> 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<Customer> 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<String, MutableList<Order>> customerNameToOrders =
this.company.getCustomers().toMap(null, null);
Assert.assertNotNull("customer name to orders", customerNameToOrders);
Verify.assertSize("customer names", 3, customerNameToOrders);
MutableList<Order> 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<Double, Customer> 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));
}
}
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
SYMBOL INDEX (84 symbols across 14 files)
FILE: src/main/java/com/gs/collections/kata/Company.java
class Company (line 27) | public class Company
method Company (line 35) | public Company(String name)
method getName (line 40) | public String getName()
method addCustomer (line 45) | public void addCustomer(Customer aCustomer)
method getCustomers (line 50) | public MutableList<Customer> getCustomers()
method getOrders (line 55) | public MutableList<Order> getOrders()
method getMostRecentCustomer (line 66) | public Customer getMostRecentCustomer()
method addSupplier (line 71) | public void addSupplier(Supplier supplier)
method getSuppliers (line 82) | public Supplier[] getSuppliers()
method getCustomerNamed (line 87) | public Customer getCustomerNamed(String name)
FILE: src/main/java/com/gs/collections/kata/Customer.java
class Customer (line 31) | public class Customer
method Customer (line 47) | public Customer(String name, String city)
method getCity (line 53) | public String getCity()
method getName (line 58) | public String getName()
method getOrders (line 63) | public List<Order> getOrders()
method addOrder (line 68) | public void addOrder(Order anOrder)
method getTotalOrderValue (line 73) | public double getTotalOrderValue()
FILE: src/main/java/com/gs/collections/kata/LineItem.java
class LineItem (line 24) | public class LineItem
method getName (line 31) | public String getName()
method setName (line 36) | public void setName(String name)
method getValue (line 41) | public double getValue()
method LineItem (line 46) | public LineItem(String name, double value)
method toString (line 52) | @Override
FILE: src/main/java/com/gs/collections/kata/Order.java
class Order (line 32) | public class Order
method Order (line 44) | public Order()
method resetNextOrderNumber (line 50) | public static void resetNextOrderNumber()
method deliver (line 55) | public void deliver()
method isDelivered (line 60) | public boolean isDelivered()
method addLineItem (line 65) | public void addLineItem(LineItem aLineItem)
method getLineItems (line 70) | public List<LineItem> getLineItems()
method toString (line 75) | @Override
method getValue (line 81) | public double getValue()
FILE: src/main/java/com/gs/collections/kata/Supplier.java
class Supplier (line 24) | public class Supplier
method Supplier (line 33) | public Supplier(String name, String[] itemNames)
method getName (line 39) | public String getName()
method getItemNames (line 44) | public String[] getItemNames()
FILE: src/test/java/com/gs/collections/kata/CompanyDomainForKata.java
class CompanyDomainForKata (line 21) | public abstract class CompanyDomainForKata
method setUp (line 25) | @Before
method setUpSuppliers (line 33) | private void setUpSuppliers()
method setUpCustomersAndOrders (line 44) | private void setUpCustomersAndOrders()
FILE: src/test/java/com/gs/collections/kata/Exercise1Test.java
class Exercise1Test (line 26) | public class Exercise1Test extends CompanyDomainForKata
method getCustomerNames (line 28) | @Test
method getCustomerCities (line 43) | @Test
method getLondonCustomers (line 56) | @Test
FILE: src/test/java/com/gs/collections/kata/Exercise2Test.java
class Exercise2Test (line 25) | public class Exercise2Test extends CompanyDomainForKata
method customerFromLondonPredicate (line 32) | @Test
method doAnyCustomersLiveInLondon (line 55) | @Test
method doAllCustomersLiveInLondon (line 65) | @Test
method howManyCustomersLiveInLondon (line 75) | @Test
method getLondonCustomers (line 86) | @Test
method getCustomersWhoDontLiveInLondon (line 97) | @Test
method getCustomersWhoDoAndDoNotLiveInLondon (line 108) | @Test
method findMary (line 120) | @Test
method findPete (line 130) | @Test
FILE: src/test/java/com/gs/collections/kata/Exercise3Test.java
class Exercise3Test (line 27) | public class Exercise3Test extends CompanyDomainForKata
method improveGetOrders (line 32) | @Test
method findItemNames (line 43) | @Test
method findCustomerNames (line 58) | @Test
FILE: src/test/java/com/gs/collections/kata/Exercise4Test.java
class Exercise4Test (line 29) | public class Exercise4Test extends CompanyDomainForKata
method findSupplierNames (line 35) | @Test
method countSuppliersWithMoreThanTwoItems (line 55) | @Test
method whoSuppliesSandwichToaster (line 66) | @Test
method filterOrderValues (line 78) | @Test
method filterOrders (line 90) | @Test
FILE: src/test/java/com/gs/collections/kata/Exercise5Test.java
class Exercise5Test (line 29) | public class Exercise5Test extends CompanyDomainForKata
method filterOrderValues (line 31) | @Test
method filterOrders (line 48) | @Test
FILE: src/test/java/com/gs/collections/kata/Exercise6Test.java
class Exercise6Test (line 27) | public class Exercise6Test extends CompanyDomainForKata
method sortedTotalOrderValue (line 33) | @Test
method maximumTotalOrderValue (line 46) | @Test
method customerWithMaxTotalOrderValue (line 56) | @Test
method supplierNamesAsTildeDelimitedString (line 66) | @Test
method deliverOrdersToLondon (line 83) | @Test
FILE: src/test/java/com/gs/collections/kata/Exercise7Test.java
class Exercise7Test (line 29) | public class Exercise7Test extends CompanyDomainForKata
method customersByCity (line 34) | @Test
method mapOfItemsToSuppliers (line 48) | @Test
method reminder (line 78) | @Test
FILE: src/test/java/com/gs/collections/kata/Exercise8Test.java
class Exercise8Test (line 35) | public class Exercise8Test extends CompanyDomainForKata
method totalOrderValuesByCity (line 42) | @Test
method totalOrderValuesByItem (line 59) | @Test
method sortedOrders (line 74) | @Test
method whoOrderedSaucers (line 87) | @Test
method ordersByCustomerUsingAsMap (line 97) | @Test
method mostExpensiveItem (line 113) | @Test
Condensed preview — 39 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (63K chars).
[
{
"path": ".classpath",
"chars": 783,
"preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n<classpath>\r\n\t<classpathentry kind=\"src\" path=\"src/main/java\"/>\r\n\t<classpathentr"
},
{
"path": ".idea/copyright/Apache.xml",
"chars": 938,
"preview": "<component name=\"CopyrightManager\">\n <copyright>\n <option name=\"notice\" value=\"Copyright &#36;today.year Goldman"
},
{
"path": ".idea/copyright/profiles_settings.xml",
"chars": 220,
"preview": "<component name=\"CopyrightManager\">\n <settings default=\"Apache\">\n <module2copyright />\n <LanguageOptions name=\"XM"
},
{
"path": ".idea/libraries/lib.xml",
"chars": 415,
"preview": "<component name=\"libraryTable\">\n <library name=\"lib\">\n <CLASSES>\n <root url=\"file://$PROJECT_DIR$/lib\" />\n <"
},
{
"path": ".idea/misc.xml",
"chars": 327,
"preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project version=\"4\">\n <component name=\"EntryPointsManager\">\n <entry_points v"
},
{
"path": ".idea/modules.xml",
"chars": 276,
"preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project version=\"4\">\n <component name=\"ProjectModuleManager\">\n <modules>\n "
},
{
"path": ".idea/runConfigurations/All_in_GSCollectionsKata.xml",
"chars": 1122,
"preview": "<component name=\"ProjectRunConfigurationManager\">\r\n <configuration default=\"false\" name=\"All in GSCollectionsKata\" type"
},
{
"path": ".project",
"chars": 395,
"preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n<projectDescription>\r\n\t<name>GS Collections Kata</name>\r\n\t<comment></comment>\r\n\t"
},
{
"path": ".settings/org.eclipse.jdt.core.prefs",
"chars": 629,
"preview": "#Fri Dec 23 13:01:22 EST 2011\r\neclipse.preferences.version=1\r\norg.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=en"
},
{
"path": "GSCollectionsKata.iml",
"chars": 681,
"preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<module type=\"JAVA_MODULE\" version=\"4\">\n <component name=\"NewModuleRootManager\" "
},
{
"path": "LICENSE-2.0.txt",
"chars": 11358,
"preview": "\n Apache License\n Version 2.0, January 2004\n "
},
{
"path": "NOTICE",
"chars": 137,
"preview": "GS Collections Kata\nCopyright 2011 Goldman Sachs\n\nThis product includes software (JUnit) developed by\nJUnit.org (http://"
},
{
"path": "README.md",
"chars": 1224,
"preview": "# GS Collections Kata\r\n\r\n## What is a Code Kata?\r\nA _kata_ is an exercise in martial arts. A code kata is an exercise in"
},
{
"path": "src/main/java/com/gs/collections/kata/Company.java",
"chars": 2746,
"preview": "/*\n * Copyright 2015 Goldman Sachs.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not"
},
{
"path": "src/main/java/com/gs/collections/kata/Customer.java",
"chars": 2117,
"preview": "/*\n * Copyright 2015 Goldman Sachs.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not"
},
{
"path": "src/main/java/com/gs/collections/kata/LineItem.java",
"chars": 1330,
"preview": "/*\n * Copyright 2015 Goldman Sachs.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not"
},
{
"path": "src/main/java/com/gs/collections/kata/Order.java",
"chars": 2441,
"preview": "/*\n * Copyright 2015 Goldman Sachs.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not"
},
{
"path": "src/main/java/com/gs/collections/kata/Supplier.java",
"chars": 1369,
"preview": "/*\n * Copyright 2015 Goldman Sachs.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not"
},
{
"path": "src/test/java/com/gs/collections/kata/CompanyDomainForKata.java",
"chars": 4437,
"preview": "/*\n * Copyright 2015 Goldman Sachs.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not"
},
{
"path": "src/test/java/com/gs/collections/kata/Exercise1Test.java",
"chars": 2228,
"preview": "/*\n * Copyright 2015 Goldman Sachs.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not"
},
{
"path": "src/test/java/com/gs/collections/kata/Exercise2Test.java",
"chars": 4683,
"preview": "/*\n * Copyright 2015 Goldman Sachs.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not"
},
{
"path": "src/test/java/com/gs/collections/kata/Exercise3Test.java",
"chars": 2204,
"preview": "/*\n * Copyright 2015 Goldman Sachs.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not"
},
{
"path": "src/test/java/com/gs/collections/kata/Exercise4Test.java",
"chars": 3473,
"preview": "/*\n * Copyright 2015 Goldman Sachs.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not"
},
{
"path": "src/test/java/com/gs/collections/kata/Exercise5Test.java",
"chars": 2844,
"preview": "/*\n * Copyright 2015 Goldman Sachs.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not"
},
{
"path": "src/test/java/com/gs/collections/kata/Exercise6Test.java",
"chars": 3234,
"preview": "/*\n * Copyright 2015 Goldman Sachs.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not"
},
{
"path": "src/test/java/com/gs/collections/kata/Exercise7Test.java",
"chars": 2981,
"preview": "/*\n * Copyright 2015 Goldman Sachs.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not"
},
{
"path": "src/test/java/com/gs/collections/kata/Exercise8Test.java",
"chars": 4666,
"preview": "/*\n * Copyright 2015 Goldman Sachs.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not"
}
]
// ... and 12 more files (download for full content)
About this extraction
This page contains the full source code of the goldmansachs/gs-collections-kata GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 39 files (57.9 KB), approximately 14.3k tokens, and a symbol index with 84 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.