InjectIntoKeyValue in Eclipse Collections

InjectIntoKeyValue — What Does It Do?

InjectIntoKeyValue implements the injectInto pattern on each key-value pair of a map. The method applies a three-argument function to each key-value pair of the map using an initial value and returns the result.

Example: Sum

@Test
public void injectIntoKeyValueSum()
{
LongIntMap map = this.newWithKeysValues(1L, 2, 3L, 4);
Long sum = map.injectIntoKeyValue(new Long(0),
(Long sum0, long eachKey, int eachValue) ->
{
return new Long((long) (sum0 + eachKey + eachValue));
});
Assert.assertEquals(new Long(10), sum);
}

Example: Product

@Test
public void injectIntoKeyValueProduct()
{
LongIntMap map = this.newWithKeysValues(1L, 2, 3L, 4);
Long sum = map.injectIntoKeyValue(new Long(1),
(Long sum0, long eachKey, int eachValue) ->
{
return new Long((long) (sum0 * eachKey * eachValue));
});
Assert.assertEquals(new Long(24), sum);
}

Example: Primitive to Object Map

@Test
public void injectIntoKeyValueCopy()
{
IntObjectMap map1;
MutableMap<?, ?> map2 = map1.injectIntoKeyValue(
Maps.mutable.empty(), target::withKeyValue);
}

Implementation

This new feature was implemented for object and primitive maps; it can be applied to PrimitivePrimitiveMaps, PrimitiveObjectMaps, ObjectPrimitiveMaps, and ObjectObjectMaps. Since Java does not support generics for primitives, implementation on the primitive side was a bit tedious. For the three-argument function taken in by injectIntoKeyValue, several function templates needed to be defined in order to generate every possible function permutation. One of the templates, ObjectObjectPrimitiveToObjectFunction, can be viewed here. If you’re interested in learning more about the need for universal generics in Java, I suggest checking out Project Valhalla.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Emilie Robichaud

Emilie Robichaud

University of Toronto graduate with majors in Computer Science and Mathematics! Always eager to explore more in the world of technology.