7 ms·
I don't really know Java, so this is made up Java/C#/something, but compare these: List<int> mapped = new List<int>(); for (int i = 0; i < list.count()
by natesm 15y ago
I don't really know Java, so this is made up Java/C#/something, but compare these:
List<int> mapped = new List<int>();
for (int i = 0; i < list.count(); i++)
{
mapped[i] = list[i] + 1;
}
Or:
List<int> mapped = list.map((x) => x + 1);
Which do you think is more elegant and readable? For a slightly more extreme example, what if we want the numbers less than 100:
List<int>filtered = new List<int>();
for (int i = 0, j = 0; i < list.count(); i++)
{
if (list[i] < 100)
{
filtered[j] = list[i];
j++;
}
}
Or this:
List<int> filtered = list.filter((x) => x < 100);
- deleted 15y ago[deleted]
- mayanksinghal 15y agoI wasn't even aware of maps and filters :) So basically, there is a lot to learn!
- jshen 15y agoI wrote a blog post with a nearly identical example. http://jaydonnell.com/blog/2011/08/07/is-your-idea-clealry-expressed-in-your-code/ http://jaydonnell.com/blog/2011/08/07/is-your-idea-clealry-e... The code gets nutty when you have to do multiple transforms on collections. There are some libraries in Java which make it more bearable. http://code.google.com/p/lambdaj/ http://code.google.com/p/lambdaj/ List<Person> sortedByAgePersons = sort(persons, on(Person.class).getAge());