Filtering arrays / lists
24th April 2021
Every application is going to need to filter a collection at some point, this is a quick code dump of how to do that in Java, Kotlin & Javascript. This is primarily looking at Arrays and Lists, not Maps. All examples are going to work off the below list of seasonal fruit and will filter them by their seasons.
All of these examples lead to a new collection being created.
Kotlin
Java
Javascript
Fruit Model
fun getAutumnFruit(fruitList : Collection<SeasonalFruit>): ArrayList<SeasonalFruit> {
//using a for loop
val result = arrayListOf<SeasonalFruit>()
for(fruit in fruitList) {
if(fruit.season == Seasons.AUTUMN) {
result.add(fruit)
}
}
return result
}
//[APPLES, CHERRIES]
fun getWinterFruit(fruitList : Collection<SeasonalFruit>): ArrayList<SeasonalFruit> {
//using filter method on collection
return fruitList.filter { it.season == Seasons.WINTER } as ArrayList<SeasonalFruit>
}
//[LEMONS, PEARS]
public ArrayList<SeasonalFruit> getSpringFruit(Collection<SeasonalFruit> fruitList) {
/*
If you are not supporting Java 8 and therefore Lambdas, a for loop is an easy option
*/
ArrayList<SeasonalFruit> result = new ArrayList<>();
for(SeasonalFruit fruit: fruitList) {
if(fruit.getSeason() == Seasons.SPRING) {
result.add(fruit);
}
}
return result;
}
//[STRAWBERRIES, LIMES, MANGOS]
public ArrayList<SeasonalFruit> getSummerFruit(Collection<SeasonalFruit> fruitList) {
/*
If you are using J8 or newer, filtering a steam is most common method
*/
return (ArrayList<SeasonalFruit>) fruitList
.stream()
.filter(fruit -> fruit.getSeason() == Seasons.SUMMER)
.collect(Collectors.toList());
}
//[ORANGES, BLACKBERRIES]
const fruitList = [
{"name": "Strawberries","season": "SPRING"},
{"name": "Limes","season": "SPRING"},
{"name": "Mangos","season": "SPRING"},
{"name": "Oranges","season": "SUMMER"},
{"name": "Blackberries","season": "SUMMER"}
]
const summerFruits = fruitList.filter(fruit => fruit.season === "SUMMER")
// [{"name": "Oranges","season": "SUMMER"}, {"name": "Blackberries","season": "SUMMER"}]
enum class SeasonalFruit(val season: Seasons) {
STRAWBERRIES(Seasons.SPRING),
LIMES(Seasons.SPRING),
MANGOS(Seasons.SPRING),
ORANGES(Seasons.SUMMER),
BLACKBERRIES(Seasons.SUMMER),
APPLES(Seasons.AUTUMN),
CHERRIES(Seasons.AUTUMN),
LEMONS(Seasons.WINTER),
PEARS(Seasons.WINTER)
}
enum class Seasons {
SPRING,
SUMMER,
AUTUMN,
WINTER
}