Why is there no Stream.flatMap(Collection) method? [duplicate] - java

This question already has an answer here:
Why can't Stream.flatMap accept a collection?
(1 answer)
Closed 5 years ago.
Currently, to convert a List<List<Foo>> to a Stream<Foo>, you have to use the following:
Stream<Foo> stream = list.stream().flatMap(fs -> fs.stream());
//or
Stream<Foo> stream = list.stream().flatMap(Collection::stream);
I think this is exactly what the method references were designed for, and it does improve readability quite a bit. Now consider this:
Stream<Bar> stream = list.stream().flatMap(fs -> fs.getBarList().stream());
Having two chained method calls, no method reference is possible, and I've had this happen to me a few times. While it is not a big issue, it seems to drift away from the method-reference brevity.
Having worked with JavaFX 8 a bit, I noticed that a constant of their API's is the convenience methods. Java is a very verbose language, and it seemed to me that simple method overloads were a big selling point for JavaFX.
So my question is, I wonder why there is no convenience method Stream.flatMap(Collection) that could be called like:
Stream<Bar> stream = list.stream().flatMap(Foo::getBarList);
Is this an intentional omission by the folks at Oracle? Or could this cause any confusion?
Note: I'm aware of the "no-opinion-based-questions policy," and I'm not looking for opinions, I'm just wondering if there is a reason that such a method is not implemented.

Because Stream is already a pretty big interface and there's resistance to making it bigger.
Because there's also the workaround list.stream().map(Foo::getBarList).flatMap(List::stream).
You can also see the original discussion at http://mail.openjdk.java.net/pipermail/lambda-libs-spec-observers/2013-April/001690.html ; I'm not seeing that option specifically discussed; it may have been discarded already at that point?

Related

Java 8 stream vs List [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I have a set of private methods that are used in a main public method (that receive a list) of a class, these methods will mainly use java 8 classic stream operations as filter, map, count e.t.c. I am wondering if creating stream single time in public api and passing to others method instead of passing list have any performance benefits or considerations as .stream() is called single time.
Calling stream() or any intermediate operation would actually do nothing, as streams are driven by the terminal operation.
So passing a Stream internally from one method to another is not bad IMO, might make the code cleaner. But dont return a Stream externally from your public methods, return a List instead ( plz read the supplied comments, might not hold for all cases)
Also think of the case that applying filter for example and then collecting to a toList and then streaming again that filtered List to only map later is obviously a bad choice... You are collecting too soon, so dont chain methods like this even internally.
In general it's best to ask for what is actually needed by the method. If every time you receive a list you make it a stream, ask for the stream instead (streams can come from things other than lists). This enhances portability and reusability and lets consumers of your api know upfront the requirements.
Ask for exactly what you need, nothing more, nothing less.

Java 8 Stream string of map calls versus combining into one [duplicate]

This question already has answers here:
Using multiple map functions vs. a block statement in a map in a java stream
(2 answers)
Closed 3 years ago.
When using Java 8 Stream API, is there a benefit to combining multiple map calls into one, or does it not really affect performance?
For example:
stream.map(SomeClass::operation1).map(SomeClass::operation2);
versus
stream.map(o -> o.operation1().operation2());
The performance overhead here is negligible for most business-logic operations. You have two additional method calls in the pipeline (which may not be inlined by JIT-compiler in real application). Also you have longer call stack (by one frame), so if you have an exception inside stream operation, its creation would be a little bit slower. These things might be significant if your stream performs really low-level operations like simple math. However most of the real problems have much bigger computational cost, so relative performance drop is unlikely to be noticeable. And if you actually perform a simple math and need the performance, it's better to stick with plain old for loops instead. Use the version you find more readable and do not perform the premature optimization.

When is length used as a method and when as property in Java? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I've seen some legacy code that uses lengthproperty on some objects and others that uses length() method. Currently I'm working with a NodeList from the org.w3c.dom package and I found that it have the getLength() method to get the numbers of elements.
My Question is how as Java developer I can know how to determine when to use length, length(), size(), getLength()? obviously it depends of the object type and the API is there for read... but the point is how the Java Development select which of that implements in their classes.
Note: In the Question When to use .length vs .length() Makoto answer's indicates that .length is a property on arrays. That isn't a method call, and length() is a method call on String. But, why is the reason? why not use ever a method or ever a property for maintain the consistency around all the API.
how would Java developers select which of [the methods] to implement in their classes?
When you implement classes that contain other objects, it's almost always going to be size(), the method provided by theCollection interface.
As far as other choices go, you should avoid exposing member variables, even final ones, because they cannot be accessed through an interface. Java gets away with it for arrays because of some JVM trickery, but you cannot do the same. Hence, length should be out: it remains in Java because it's not possible to change something that fundamental that has been in the language from day one, but it's definitely not something one should consider when designing new classes.
When you implement your own type that has length (say, a rectangle or a line segment) you should prefer getLength() to length() because of Java Beans naming conventions.
obviously it depends of the object type and the API is there for read...
You already have answered your question yourself: look in the API documentation of whatever class you are using.
but the point is how the Java Development select which of that implements in their classes.
The classes in Java's standard library have been developed over a long period of time by different people, which do not always make the same choice for the name of methods, so there are inconsistencies and unfortunately you'll just have to live with that.
There is no clear rule, otherwise we wouldn't see such a mixup in the jdk itself. But here are some things to consider when making such a design decision.
Don't worry to much. It is a minor thing and won't make to much of a difference. So when you think longer then 5 minutes about this, you are probably wasting money already.
Use getters when a frameworks need them. Many frameworks depend on the getter style. If you need or want such frameworks to work nicely with your class it might be beneficial to use that style.
Shorter is better. the 'get' part doesn't increase clarity. It just generates to characters of noise to the source code, so if you don't need it for some reason, don't use it.
Methods are easier to evolve. Length is often a quantity that is not set directly but somehow computed. If you hide that behind a method it gives you the flexibility to change that implementation later on, without changing the API.
Direct field accesses should be a tiny bit faster, but if you aren't working on high volume online trading or something, the difference isn't even worth thinking about. And if you do you should do your own measurements before making a decision. The hotspot compiler will almost for sure inline the method call anyways.
So if there aren't any external forces driving you in a different direction I would go with 'length()'
According to OOPS principles, length should be attribute and getLength() should be method. Also length attribute should be encapsulated should be exposed through methods, so getLength() sounds more appropriate.
Unfortunately not all Java library classes follow standards. There are some exceptions and this is one among them.
In a pure OO language it should be probably always a method like length(). So in a class hierarchy you can override the attribute length.
But Java is not pure OO. And the main reason for fields (.length) vs method (length()) is/was performance issues.
And even Sun/Oracle programmers did some bad class design.

What is the java equivalent of VBA's "With" statement [duplicate]

This question already has answers here:
WITH statement in Java
(8 answers)
Closed 8 years ago.
In VB / VBA you can do something like this:
With person
.Name = "John"
.Age = 32
End With
But in java I can't figure out how or if that functionality exists. Everything I see seems to just repeat the object references, like this:
person.setName("John");
person.setAge("32");
If it doesn't exists, is there at least some methodology to cut down on the repetition?
If it doesn't exists, is there at least some methodology to cut down on the repetition?
Nope, not really - not unless you control the type.
If you do control the type, you can make the set methods return this, allowing you to chain the method calls. This is often useful for builder types:
Person person = Person.newBuilder().setName("John").setAge(32).build();
(You can just make your types mutable rather than separating builder types from immutable non-builder types, but I'm just a fan of immutability...)

Besides dynamic typing, what makes Ruby "more flexible" than Java? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I've been using Java almost since it first came out but have over the last five years gotten burnt out with how complex it's become to get even the simplest things done. I'm starting to learn Ruby at the recommendation of my psychiatrist, uh, I mean my coworkers (younger, cooler coworkers - they use Macs!). Anyway, one of the things they keep repeating is that Ruby is a "flexible" language compared to older, more beaten-up languages like Java but I really have no idea what that means. Could someone explain what makes one language "more flexible" than another? Please. I kind of get the point about dynamic typing and can see how that could be of benefit for conciseness. And the Ruby syntax is, well, beautiful. What else? Is dynamic typing the main reason?
Dynamic typing doesn't come close to covering it. For one big example, Ruby makes metaprogramming easy in a lot of cases. In Java, metaprogramming is either painful or impossible.
For example, take Ruby's normal way of declaring properties:
class SoftDrink
attr_accessor :name, :sugar_content
end
# Now we can do...
can = SoftDrink.new
can.name = 'Coke' # Not a direct ivar access — calls can.name=('Coke')
can.sugar_content = 9001 # Ditto
This isn't some special language syntax — it's a method on the Module class, and it's easy to implement. Here's a sample implementation of attr_accessor:
class Module
def attr_accessor(*symbols)
symbols.each do |symbol|
define_method(symbol) {instance_variable_get "##{symbol}"}
define_method("#{symbol}=") {|val| instance_varible_set("##{symbol}", val)}
end
end
end
This kind of functionality allows you a lot of, yes, flexibility in how you express your programs.
A lot of what seem like language features (and which would be language features in most languages) are just normal methods in Ruby. For another example, here we dynamically load dependencies whose names we store in an array:
dependencies = %w(yaml haml hpricot sinatra couchfoo)
block_list %w(couchfoo) # Wait, we don't really want CouchDB!
dependencies.each {|mod| require mod unless block_list.include? mod}
It's also because it's a classless (in the Java sense) but totally object oriented (properties pattern) so you can call any method, even if not defined, and you still get a last chance to dynamically respond to the call, for example creating methods as necessarry on the fly. Also Ruby doesn't need compilation so you can update a running application easily if you wanted to. Also an object can suddenly inherit from another class/object at anytime during it's lifetime through mixins so it's another point of flexibility. Anyways I agree with the kids that this language called Ruby , which has actually been around as long as Java, is very flexible and great in many ways, but I still haven't been able to agree it's beatiful (syntax wise), C is more beatiful IMHO (I'm a sucker for brackets), but beauty is subjective, the other qualities of Ruby are objective
Blocks, closures, many things. I'm sure some much better answers will appear in the morning, but for one example here's some code I wrote ten minutes ago - I have an array of scheduled_collections, some of which have already happened, others which have been voided, canceled, etc. I want to return an array of only those that are pending. I'm not sure what the equivalent Java would be, but I imagine it's not this one-line method:
def get_all_pending
scheduled_collections.select{ |sc| sc.is_pending? }
end
A simpler example of the same thing is:
[0,1,2,3].select{|x| x > 1}
Which will produce [2,3]
Things I like
less code to get your point across
passing around code blocks (Proc, lambdas) is fun and can result in tinier code. e.g. [1, 2, 3].each{|x| puts "Next element #{x}"}
has the scripting roots of PERL.. very nice to slice n dice routine stuff like parsing files with regexps, et. all
the core data structure class API like Hash and Array is nicely done.
Metaprogramming (owing to its dynamic nature) - ability to create custom DSLs (e.g. Rails can be termed a DSL for WebApps written in Ruby)
the community that is spawning gems for just about anything.
Mixins. Altering a Ruby class to add new functionality is trivially easy.
Duck typing refers to the fact when types are considered equivalent by what methods them implement, not based on their declared type. To take a concrete example, many methods in Ruby take a IO-like object to operate on a stream. This means that the object has to implement enough functions to be able to pass as an IO type object (it has to sound enough like a duck).
In the end it means that you have to write less code than in Java to do the same thing. Everything is not great about dynamic languages, though. You more or less give up all of the compile-time typechecking that Java (and other strongly/statically typed languages) gives you. Ruby simply has no idea if you're about to pass the wrong object to a method; that will give you a runtime error. Also, it won't give you a runtime error until the code is actually called.
Just for laughs, a fairly nasty example of the flexibility of the language:
class Fixnum
def +(other)
self - other
end
end
puts 5 + 3
# => 2

Categories