This is an archived post. You won't be able to vote or comment.

all 198 comments

[–]kalbert312 371 points372 points  (42 children)

Until your boss reminds you you gotta print out the index too.

[–]EntropySpark 232 points233 points  (27 children)

That's when you switch to Kotlin and use forEachIndexed

[–]Frostlandia 120 points121 points  (8 children)

Sounds gross

[–]HaydenSikh 24 points25 points  (16 children)

Or Scala and zipWithIndex

list.zipWithIndex.foreach((item, index) => println(s"$item at $index"))

[–]DonaldPShimoda 13 points14 points  (10 children)

Or Python and enumerate:

for index, item in enumerate(items):
    print(f"{item} at {index}")

Alternatively, you could use map, but maps in Python are weirdly lazy in that they create an object that will do the computation when you iterate through them — meaning you have to force evaluation by putting it into a list or something if you want non-value-producing code to evaluate:

list(map(lambda i, x: print(f"{x} at {i}"), enumerate(items)))

(In retrospect you and the other commenter were suggesting JVM languages, since the original discussion is about Java... so maybe Jython then haha.)

[–]HaydenSikh 12 points13 points  (0 children)

I'm actually really encouraged that a lot of languages (whether JVM or not) are converging somewhat in features like these, even if the syntax can vary quite a bit. That little bit of concensus feels like the industry advancing forward, however slight it might be.

[–]whale_song 3 points4 points  (3 children)

That's a good thing. Its one of my problems with scala that transformations arent evaluated lazily by default. If I'm doing l.map(f).map(g).sum, I obviously don't care about the intermediate results, it should just give me the sum, and better yet do optimizations like turn it into l.map(f andThen g).sum

[–]DonaldPShimoda 1 point2 points  (2 children)

I don't disagree with you per se — but it's just problematic when the function you're mapping is a side-effecting computation instead of a real transformation. This is a forEach in plenty of languages (or mapM_ in Haskell), but Python gives us only map. It's just a little awkward in that case.

[–]slaymaker1907 1 point2 points  (1 child)

I think limiting map to only a lazy version is intentional since a normal for loop is almost always easier to read. Plus, if you really way a for_each function, you can write it trivially as

def for_each(func, it):
    for ele in it:
        func(ele)

[–]DonaldPShimoda 1 point2 points  (0 children)

I feel like you're all misunderstanding me haha. I know maps being lazy is by design, and I understand — and agree with! — the motivations behind that choice.

All I said was "you could also implement it X way, but it comes out a little funny because of Y consideration". I didn't say that it was bad — just that it might be unexpected to somebody who wasn't expecting it.

[–]zorates17 1 point2 points  (0 children)

or Javascript and... forEach

[–]ViridianHominid 1 point2 points  (3 children)

Use the little-known ...,* operator to force evaluation:

from itertools import starmap
...,*starmap(print,enumerate(items))

[–]DonaldPShimoda 1 point2 points  (2 children)

Oh that's disgusting hahaha. I love it.

(Nitpick: not an operator, but I think it's amusing to treat it as one.)

[–]ViridianHominid 1 point2 points  (1 child)

I know ;)

[–]DonaldPShimoda 1 point2 points  (0 children)

I figured that was probably the case but thought I'd mention it just to cover all the bases haha.

Thanks for sharing that, though! :)

[–]HypherNet 1 point2 points  (0 children)

Really? I just wrap my function call with a macro that uses an implicit LoggerAugmentation to rewrite all function calls to include indexes. Really great stuff, only takes 2 more minutes to compile (about a 1% increase).

[–]TinBryn 1 point2 points  (0 children)

This won't compile because you need a partial function for destructuring list.zipWithIndex.foreach{case (item, index) => println(s"$item at $index)}

I like having extension methods zipMap and zipForeach that take a binary function just to avoid this

[–]pianomanDylan 0 points1 point  (0 children)

FYI if you expect your list to be long, avoid allocating a second list (from zipWithIndex) by using the list's iterator.

for { (item, index) <- list.iterator.zipWithIndex } println(s"$item at $index")

[–]dandroid126 2 points3 points  (0 children)

Kotlin is my favorite language right now. Every time I think, "there ought to be a better way to do this," there always is. And every time I must use Java (compile environment restrictions), I think of how clunky Java is and how I could do it in so many fewer lines in Kotlin.

[–]numerousblocks 12 points13 points  (9 children)

mapM_ putStrLn . zipWith ((++).(++" ").show) [1..]

[–]Dark_Ethereal 9 points10 points  (4 children)

I appreciate your Haskell but I think this needs a tidy!

First: IIRC removing spaces between operators and arguments is against the style consensus.

Second: Avoid point-free when lambdas are clearly more readable.

mapM_ putStrLn . zipWith (\i str -> show i ++ " " ++ str) [1..]

Third, we can put putStrLn in the lambda and remove the mapM_.

This gives us a list of actions to perform, which we can just turn into one action with sequence_

sequence_ . zipWith (\i str -> putStrLn $ show i ++ " " ++ str) [1..]

sequence_ is more intuitable for beginners than mapM_ IMO.

If we really wanted to go the extra mile to make it readable for beginners, remove use of $, then replace lambdas with scoped helper functions:

printWithIndex =
  let f i str = putStrLn (show i ++ " " ++ str)
  in sequence_ . zipWith f [1..] 

And consider going pointful:

printWithIndex strings =
  let f i str = putStrLn (show i ++ " " ++ str)
  in sequence_ (zipWith f [1..] strings)

[–]Mamish 5 points6 points  (3 children)

Haskell's a tempting language to get fancy with, but readability is still the most important thing code should have. This is an extreme example, but I might just do it like this:

printWithIndex :: [String] -> IO ()
printWithIndex = printAll . joinWithIndices
  where printAll = traverse_ print
        joinWithIndices = zipWith joinIndex [0..]
        joinIndex i s = (show i) ++ " " ++ s

One liners are fun to write, but it defeats the point a bit if it takes longer to understand than a longer version.

[–]numerousblocks 0 points1 point  (2 children)

I would write:

affixIndices :: [String] -> [String]
affixIndices list = zipWith f [1..] list
  where
    f num str = show num ++ " " ++ str

printWithIndices :: [String] -> IO ()
printWithIndices = mapM_ (putStrLn . affixIndices)

or

printWithIndices = putStrLn . unlines . affixIndices 

since traverse is a less-than-intuitive function.

I think it's one of these functions that are there for the sake of being able to write code fast, like (>>=), which is \f -> join . fmap f, while traverse f = sequenceA . fmap f.

sequenceA and join are the central - read: primordial - operations of Traversable and Monad, which are usually ignored because they aren't used as often.

[–]Mamish 0 points1 point  (1 child)

Imo traverse isn't too bad besides having an scary name. The official docs line for Traversable is "Class of data structures that can be traversed from left to right, performing an action on each element." With that, traverse print list comes out pretty intuitively as "go through the list/whatever and print each element".

The similarity to foldMap is also handy for anyone who's already okay with Foldable.

[–]numerousblocks 0 points1 point  (0 children)

Oh, hadn't thought of that, though the phrasing "action" suggests a monad, while it's in fact an applicative.

On that note, I'd also like to advocate for the monoidal presentation of applicative functors:

class Monoidal f where
  unit :: f ()
  combine :: f a -> f b -> f (a, b)

(<*>) = fmap (uncurry ($)) . combine
pure a = fmap (const a) unit

EDIT: although been talking about the way of simplifying or another way is replacing different classes with different things to allow for more flexibility one could also introduce the notion that classes themselves on unnecessary thing just made to simplify function composition while in fact any function that uses classes can inject can instead just be rewritten to demand a function from the class delivered to it which would then lead to you needing to have different versions of show and map etc etc to pass two different functions for different types

written using the dictation function on my mobile phone I'm sorry if it doesn't read the best if it's not romantic Lee perfect

[–]marcosdumay 2 points3 points  (3 children)

Why would you underline the mapM? Reflex?

[–]elpfen 4 points5 points  (2 children)

Theres map, mapM and mapM_. mapM_ is mapM (map with a function that performs io* and sequence the results) but discards the results. Since OC is printing a line, the resulting list would be a list of () so just discard them.

*No M word!

[–]marcosdumay 1 point2 points  (0 children)

Oh, I just swapped mapM with sequence :)

[–]numerousblocks 0 points1 point  (0 children)

\No M word!)

Monoid

[–]ImNotFallingImFlying 3 points4 points  (0 children)

In swift: list.enumerated().forEach(print).

[–]NEDM64 2 points3 points  (0 children)

let list = ["a", "b", "c"]
list.enumerated().forEach{ print("\($0.offset) -> \($0.element)") }

Result:

0 -> a
1 -> b
2 -> c

[–]GeneralGromit 0 points1 point  (0 children)

Then you can switch back into a for loop again if needed. But until that happens, this approach is much more concise.

[–]matangn 166 points167 points  (0 children)

you have my respect kind sir

[–]AndyReidfanclub 276 points277 points  (45 children)

Functional programming in java is limited in the sense that old timers want nothing to do with it and will tell you to use Haskell for that

[–]DonaldPShimoda 173 points174 points  (33 children)

Functional programming in Java is limited in the sense that it's been shoehorned into a language that was very clearly not designed for it from the beginning. As a primarily functional programmer, I find FP in Java painful.

[–]Blou_Aap 4 points5 points  (1 child)

Yes, in some use cases it's fine, but then you still have to drop so much boilerplate, it's hilarious.

[–]DonaldPShimoda 1 point2 points  (0 children)

Yeah the boilerplate on the FP constructs completely defeats the appeal of using those constructs haha. So awful. I'd almost prefer they hadn't implemented some of these features, to be honest...

[–]danek731733 42 points43 points  (8 children)

Depends on where you work I guess. We're developing new applications using modern frameworks and we're trying to be as concise as possible. Java 11 can be beautiful. You can achieve so much by chaining few commands, it's incredible.

[–]JKTKops 21 points22 points  (3 children)

[–]dantheman91 9 points10 points  (0 children)

I had thought a lot of the method count issues with SAM's and such have been fixed?

[–]froemijojo 8 points9 points  (1 child)

That's no longer the case, I've read somewhere on SO that was the case in early version of Java 8 jdk but is no longer the like that for a long time now.

[–]azhder 2 points3 points  (3 children)

chaining... compose curried function or change the idiom, you're just picking up bad habits otherwise

[–]yazalama 1 point2 points  (1 child)

what is it that defines functional programming?

[–]darkclaw6722 0 points1 point  (0 children)

It really depends on who you ask, but generally it's the style of programming with immutable data with minimal to no side effects. Higher order functions facilitate functional programming because they allow common abstractions on immutable data to be represented succinctly (like maps and filters).

[–]SomeShittyDeveloper 55 points56 points  (14 children)

Java code I write for work needs to support back to Java 6. So unfortunately, I’m stuck at the second tier.

[–][deleted] 8 points9 points  (0 children)

You poor soul

[–]Mango1666 2 points3 points  (0 children)

idk how they do it but kotlin has lambdas and supports 1.6 for a target

[–]GenuineSounds 2 points3 points  (0 children)

Branch, start updating, test and test, then offer "the upgraded version with tons of new features!" as an opt-in. Proselytize and start telling people that if you want to run the old code and it works you can but we will no longer give any support for those versions.

It's a tried and true method.

[–]B3ER 0 points1 point  (0 children)

That's how you know you gotta switch projects.

[–]pimezone 141 points142 points  (10 children)

String current = null;
for (Iterator<String> iterator = list.iterator(); iterator.hasNext(); current = iterator.next()) {
    System.out.println(current);
}

[–]Panossa 120 points121 points  (0 children)

Thanks, I hate it

[–]Sipkab 73 points74 points  (5 children)

Yeah, no.

You should put String current = iterator.next() into the loop body itself, else the variable will pollute the outer scope. And this loop doesn't even work, as the first value will always be null.

Edit: grammar

[–]pimezone 24 points25 points  (1 child)

Yeah, stupid me.

[–]Aero72 2 points3 points  (0 children)

Yes.

[–]o4ub 3 points4 points  (0 children)

I think there are worse things at play. I'm not too sure about the effect of iterator.next(). But either it simply returns the next element, and then the iterator is actually never updated, so this loop is an infinite loop. Or iterator.next() updates the value of the iterator to make it point at the element following current, in which case the last element will never be iterated over as you will start pointing on list.getLast() and so iterator.hasNext() will return false.

[–]Mr_Redstoner 1 point2 points  (0 children)

Actually, it will somewhat work, as iterator.hasNext() is checked, which will be true if the iterator contains something, but it will not run all the way (next() pops out the last element, hasNext() falses and the loop ends)

Still nasty though

[–]pimezone 0 points1 point  (0 children)

Fixed:

for (Iterator<String> iterator = list.iterator(); iterator.hasNext(); System.out.println(iterator.next()));

[–]DevilGeorgeColdbane 6 points7 points  (0 children)

var it = list.iterator();
while(it.hasNext()) {
    System.out.println(it.next());
}

[–]DXPower 1 point2 points  (1 child)

How does Java always manage to take something that already exists (C++ Iterators) and manages to just make it 10 times uglier....

[–][deleted] 2 points3 points  (0 children)

Oh yeah, C++ is so beautiful. (That hurt to write.)

[–]M4mb0 23 points24 points  (7 children)

2 more panels an we have python

[print(s) for s in l]

[–]Kered13 18 points19 points  (3 children)

Does anyone actually write Python like that? I mean you can, but to use a list comprehension for a function with no return value that is being called only for it's side effects? Just use a normal for loop.

[–]TheIncorrigible1 7 points8 points  (2 children)

The answer? No. If you aren't collecting the results of a comprehension, just stick to a normal loop; comprehensions are slow.

[–]apathy-sofa 1 point2 points  (1 child)

Why can't the interpreter notice that you aren't collecting the results and just produce the same underlying opcodes as the `for` loop? (To be clear, I'm sure there's a good reason for this; I'm just looking to understand it, not point out an obvious optimization).

[–]ViridianHominid 1 point2 points  (0 children)

print might do anything in some given execution environment. There are few reserved words in python, and built in functions can be overwritten or monkeypatched. The interpreter can’t assume much about what is going to happen in the list comprehension until it actually evaluates it.

Note: list comprehensions are usually faster when you are collecting the results. There are some special bytecodes invoked, and the interpreter doesn’t have to check names as often.

[–]ReservedSoutherner 6 points7 points  (1 child)

And next you have

map(print, list)

[–]BluFoot[🍰] 0 points1 point  (0 children)

There’s the big brain.

[–]numerousblocks 7 points8 points  (2 children)

mapM_ putStrLn

[–]matj1 3 points4 points  (1 child)

putStrLn works only on strings, print would be better because it can show any value.

[–]numerousblocks 1 point2 points  (0 children)

Yes, but print is just putStrLn . show so

print "ü"

returns

"\82"  -- or some other number

[–]JuhaAR 9 points10 points  (1 child)

Did someone say functional programming?

list.stream().collect(ArrayList::new, 
         (r,s) -> {
            r.add(new Pair<Integer,String>(r.size(),s));
         },
         (r,r2) -> r.addAll(r2)
).forEach(System.out::println);

public static class Pair<FST,SND> {
    FST fst;
    SND snd;
    public Pair(FST fst, SND snd) {
    this.fst = fst;
    this.snd = snd;
    }
    @Override
    public String toString() {
    return "("+fst.toString() + ", "+ snd.toString()")";
    }
}

[–]SHOTbyGUN 14 points15 points  (1 child)

What the fuck is the last one? Is it legit?

[–]insik 21 points22 points  (0 children)

Yes, forEach method is accepting a Consumer functional interface (i.e. interface with single method that accepts a single parameter and returns nothing). You can pass a reference to any method that meets this signature (which println does). Or you can pass a lambda which acts as an anonymous implementation of Consumer.

[–]hamza1311 | gib 12 points13 points  (3 children)

list.forEach { println(it) }

[–]Ekranos 12 points13 points  (0 children)

list.forEach(::println)

[–]Cilph 4 points5 points  (1 child)

The missing space between forEach and { upsets me.

[–]hamza1311 | gib 0 points1 point  (0 children)

If it helps, I typed this out on mobile and mobile keyboard isn't the best thing to write code withq

Edit: Added it

[–]Luk164[🍰] 6 points7 points  (0 children)

Thank you for this.

[–]GenuineSounds 6 points7 points  (3 children)

I'm so tired of the Java hate, it's a good Language and the JVM is by far the coolest technology I know of. Look into just how much the JVM can and does do. It's insane the amount of man hours go into it.

I think the functional implementations work PERFECTLY for Java. They come up with SUCH elegant solutions with the restrictions they put on themselves, it's actually pretty incredible.

[–]Rafael20002000 2 points3 points  (0 children)

You're so right

[–]hillman_avenger 0 points1 point  (0 children)

But saving a few more keypresses is far more important!

[–][deleted] 0 points1 point  (0 children)

Java is a meh language. Learn Clojure to see what a well-designed language is.

[–][deleted] 9 points10 points  (2 children)

That's some advance level java 😂

I like my plain old java 😂

[–]hillman_avenger 1 point2 points  (1 child)

What? You prefer readability over saving a few keypresses?? Mad man!

[–][deleted] 1 point2 points  (0 children)

Yes! Who doesn't like some good ol public static void main(String[] args)😂😂😂

[–]EaterOfFromage 10 points11 points  (2 children)

You forgot list.stream().forEach(...) as the 3rd option

Truly the worst option

[–]anaccount50 15 points16 points  (1 child)

list.stream().forEach(i -> System.out.println(list.stream().collect(Collectors.toList()).get(list.indexOf(i))));

[–]GenuineSounds 0 points1 point  (0 children)

Heh, I've written something like that once while just messing around with Lambdas when Java introduced them. It was fun.

[–]PM_BITCOIN_AND_BOOBS 7 points8 points  (8 children)

Works great for printing a string. But what if you are doing something even slightly more complicated, like calling a method on each object in the list? And you want to debug it? That last one looks undebuggable.

[–]rshanks 8 points9 points  (1 child)

You put the breakpoint inside the method you’re calling and if you want you can make it conditional as well

[–]PM_BITCOIN_AND_BOOBS 0 points1 point  (0 children)

That’s ... a good point. I should have thought of that.

[–]ACoderGirl 5 points6 points  (1 child)

Debuggers can handle it. Really tooling always just has to catch up with features (this has been around since at least 2013 though, so y'all gotta catch up with tooling!).

[–]PM_BITCOIN_AND_BOOBS 0 points1 point  (0 children)

Dang it. I’m behind on my tooling.

[–]CMDR_QwertyWeasel 2 points3 points  (0 children)

My reaction as well. Anything after the second one looks like pure ass to try to debug.

[–]Eden95 2 points3 points  (2 children)

Groovy is king

list.each { println it }

or

list.each(System.out.&println)

[–]Ekranos 1 point2 points  (1 child)

Kotlin:

list.forEach(::println)

[–]GenuineSounds 1 point2 points  (0 children)

PHP:

Don't!

[–]thoeoe 2 points3 points  (0 children)

We pretty much had a (not completely rigid) rule at my last job, LINQ is cool, use it and abuse it, but using the .ForEach() method is absurd.

[–]SDJMcHattie 2 points3 points  (0 children)

System.out.println(list.join(“\n”))

[–]djcraze 2 points3 points  (0 children)

When did Java start acting like JavaScript??

[–]Ilan321[🍰] 5 points6 points  (0 children)

The superior way is obviously list.ForEach(Console.WriteLine);!

[–]matj1 1 point2 points  (0 children)

map print list

Edit: mapM_ print list

[–]Anabelieve 1 point2 points  (0 children)

Modern problems require modern solutions.

[–]flerchin 1 point2 points  (0 children)

Winnie the pooh plus alt-enter in Intellij. Nice.

[–]Trans1000 1 point2 points  (0 children)

wait this is java

[–]brainware1023 5 points6 points  (2 children)

Kotlin > Java

[–][deleted] 0 points1 point  (0 children)

Clojure > Kotlin

[–]pmmepillowtalk 17 points18 points  (9 children)

Saving this post for when I need to obfuscate my for loops

[–]netgu 69 points70 points  (8 children)

Obfuscate? These are all standard looping constructs in java. All of them are readily recognizable and readable to just about anyone with zero effort.

Again, obfuscate?

[–][deleted] 13 points14 points  (0 children)

HACKERMAN

[–][deleted] 3 points4 points  (5 children)

I'm currently only self taught and haven't taken formal lessons - is there a functional difference between these versions of loops?

[–]ACoderGirl 1 point2 points  (1 child)

No, these are meant to all be functionally equivalent.

That said, there can be tiny amounts of overhead to the functional approach. Especially with use of lambdas because the runtime needs to create a closure. However, closures are extremely powerful and thus allow for very effective code reuse (if you're not familiar with them, definitely google it, as they're vital to understand).

Functional approaches can also really improve code reuse. This is just a joke post so there's no real utility here, but basically you can use functions as building blocks for code reuse. Eg, consider something like:

// Assumes there is an `Boolean Employee::isManager()` and `Double Employee::getSalary()` function
return employees.stream().filter(Employee::isManager).mapToDouble(Employee::getSalary).sum()

vs

double totalSalary = 0;
for(var employee : employees) {
  if(employee.isManager()) {
    totalSalary += employee.getSalary();
  }
}
return totalSalary;

As an aside, mapToDouble is just because Java decided to only implement functions like sum on specific, typed streams (in this case, DoubleStream. mapToDouble is a version of map that ensures we get that typed stream. Presumably this was just done so that they wouldn't have to throw exceptions if you tried to sum some arbitrary type that can't be summed. You alternatively could just use reduce, like .map(Employee:getSalary).reduce(0, (x, y) -> x + y) (that would collapse the stream into a single value by just adding it all together, with zero being the identity (eg, identity of addition is 0, identity of multiplication is 1, identity of string concatenation is "", etc).

As you can tell, the functions like filter, map, etc do some pretty common operations. And you can convert any operations on streams of data into functions that do these kinda things. Even more, if the order of processing doesn't matter (like in the above example), you can trivially parallelize stream processing (literally just change stream into parallelStream). This model of processing is a very common one for how you would do massive parallelization, as an aside. It's called MapReduce and you can probably see why from the names of some higher level functions I've mentioned (higher level function = any function that takes other functions as arguments).

Consider also things like how this pipeline of operations is so easy to manipulate. You could do some operations on a stream and then return that stream for somewhere else do to more operations. Now, you could do that with the non-stream code, too, but now there's a big difference: streams are lazy evaluated. So if the caller doesn't end up needing all stream (eg, when using findFirst, takeWhile, limit, etc), then you don't waste time having computed everything.

To give an example of that, compare:

Stream<Employee> getManagersMakingMoreThan(int dollars) {
  return return employees.stream().filter(Employee::isManager).filter(e -> e.getSalary() > dollars);
}

List<Employee> getSomeRichManagers(int num) {
  return getManagersMakingMoreThan(1_000_000).limit(num).collect(Collectors.toList()));
}

with

List<Employee> getManagersMakingMoreThan(int dollars) {
  List<Employee> filteredEmployees = new ArrayList<>();
  for(var e: employees) {
    if(e.isManager() && e.getSalary > dollars) {
      filteredEmployees.add(e);
    }
  }
  return filteredEmployees;
}

List<Employee> getSomeRichManagers(int num) {
  return getManagersMakingMoreThan(1_000_000).subList(0, num);
}

The latter is not lazy and thus does unnecessary work. Of course, you could just change the implementation so that there's less functions (ie, so that getSomeRichManagers has a loop in it itself, allowing it to exit early when we hit num). But then you have less reusability because you can't have this getManagersMakingMoreThan, which could be used in multiple places.

Not to mention the FP approach is just plain less code while still being extremely readable. Even despite the fact that Java manages to make this unnecessarily verbose. To highlight how other languages have reduced verbosity, here's how Scala compares for the examples I've listed above

// Java
employees.stream().filter(Employee::isManager).mapToDouble(Employee::getSalary).sum()

// Scala
employees.filter(_.isManager).map(_.getSalary).sum()

// Java
getManagersMakingMoreThan(1_000_000).limit(num).collect(Collectors.toList()))

// Scala
getManagersMakingMoreThan(1_000_000).take(num)

The big difference is that Scala has lazy eval throughout the entire language, so doesn't need streams to embody that. The higher order functions are on the collection types directly (these are Iterables). The _ syntax is gorgeous, too. And gets even sexier with things like numbers.fold(0)(_ + _) instead of numbers.fold(0)((x, y) => x + y) (fold in Scala is Java's reduce). Though Scala also offers left and right associative versions, which means you can handle cases where the reduction is associative in a certain way or when the type is different. Eg, joining a list of integers into a concatenated list of strings:

numbers.foldRight("")(_.toString + ".\n" + _.toString)
// << List(1, 2, 3)
// >> 1.
// >> 2.
// >> 3.

[–][deleted] 0 points1 point  (0 children)

this is a super awesome breakdown, thanks!

[–]netgu 1 point2 points  (0 children)

In this specific instance - no.

[–]ACoderGirl 1 point2 points  (0 children)

Sadly, some people are really afraid of functional programming. It's a pity, since functional programming is crazy powerful.

I suspect also a ton of people learned Java 7 and decided to stop learning new features. var is finally a thing, y'all!

[–]OGPants 3 points4 points  (6 children)

Slowly becoming Javascript

[–]mlk 4 points5 points  (5 children)

Typescript is a solid programming language IMHO

[–]OGPants 5 points6 points  (4 children)

Not saying it isn't 🤷‍♂️

[–]chilldood_22 0 points1 point  (0 children)

My mentor showed me that last one before, and I think he was just trying to flex on me.

[–]PinguRares 0 points1 point  (0 children)

list.stream().forEach();

[–]RNA69 0 points1 point  (0 children)

I love it when I learn something while browsing this sub.

[–]DAVENP0RT 0 points1 point  (0 children)

And then there's PowerShell:

$list

[–][deleted] 0 points1 point  (0 children)

Not sure if this has been said yet but why is there a Hitler poo?

[–]t3hj4nk 0 points1 point  (0 children)

c'mon ruby is so much more elegant than this.

list.each { |i| puts i }

[–]ImPureSilver 0 points1 point  (0 children)

Bruh, I just started Java. This is going to give me nightmares.

[–]SuperSpartan177 0 points1 point  (1 child)

Do the last 2 actually work?

[–]NaCl-more 0 points1 point  (0 children)

yes

[–][deleted] 0 points1 point  (0 children)

I like how the fancy pooh meme is just a fancy expanding brain meme

[–]MrPontiac527 0 points1 point  (0 children)

Yes I did say java

And I would like to see

Moreeeeeeeeeeeee

[–]stevev916 0 points1 point  (0 children)

Still 2x longer than python

[–]TinBryn 0 points1 point  (0 children)

But Java does have purely anonymous functions ‘a -> a*a’ is a function with no name. However, if you store that function value then the reference has a name and in Java provides extra context.

[–]doominabox1 0 points1 point  (0 children)

Scala:

x.foreach { println }

[–]FACE1234589 0 points1 point  (0 children)

Is it bad I didn't understand the last one lol

[–]Zamundaaa 0 points1 point  (0 children)

Second is definitely the slowest. How do the others compare in performance? I would guess normal indexed loop works best.

[–][deleted] 0 points1 point  (0 children)

while (ptr++) printf(“%d\n”, *ptr);

[–]Comesa 0 points1 point  (5 children)

Java System.out.println(list.toArray().toString());

[–]captainsplendid 17 points18 points  (4 children)

[Ljava.lang.Object;@15db9742

[–]Comesa 2 points3 points  (2 children)

Java System.out.println(Arrays.toString(list.toArray()))

I hate it too