Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking us to recommend or find a tool, library or favorite off-site resource are off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead, describe the problem and what has been done so far to solve it.
Closed 8 years ago.
Improve this question
Is there a good library for functional programming in Java?
I'm looking for stuff like Predicate and List.Find() (as a static method). Not complicated to implement, but it would be nice to find a reusable library here.
FunctionalJava is the best known library; it makes use of Java closures (BGGA) for examples:
final Array<Integer> a = array(1, 2, 3);
final Array<Integer> b = a.map({int i => i + 42});
arrayShow(intShow).println(b); // {43,44,45}
EDIT
Check also lambdaj.
Further EDIT
BGGA is entirely optional. It just makes for nicer syntax.
Scala is a functional programming language that is fully compatible with Java (runs through the JVM). It offers a beautiful mix of object-oriented and functional techniques along with many improvements over Java in generics and concurrency. Some even say it could replace Java.
Java Libraries
There are libraries that can help you do this, by already doing the legwork for you and hiding the arcane things:
Mature / Established Libraries
Functional Java
Google guava
LambdaJ
More Obscure / Experimental Libraries
Fun4J
JCurry
OCaml-Java
Jambda
Bolts
These will allow you to write Java code with a more functional approach and possibly more familiar syntax and semantic, as you'd expect from an FP-competent language. Within reason, that is.
JVM Languages
And obviously, you can implement a functional language on top of Java. So that you can then use that one as your FP language. Which is a bit of a higher-level of abstraction than what you asked for, but relatively within context (though I'm cheating a bit here, granted).
For instance, check out:
Quite Mature Languages
Clojure
Scala
Less Mature or More Obscure Languages
Frege
Jaskell
Further Reading
You may also want to read or watch these articles or videos:
Functional Progamming in the Java Language, IBM DeveloperWorks (2004)
Functional Programming Java, Lambda the Ultimate (2004)
Functional Programming: a Pragmatic Introduction, InfoQ/CodePalousa (2011)
Taken from my P.SE answer to "Is Functional Programming Possible in Java?"
Google collections has a decent selection of functional-programming style utility methods.
Some classes of interest are Iterables, Iterators, Function, Functions, etc
It also has a bunch of collection classes as well!
Functional Java is one that's worth taking a look at and FunctionalJ is another.
If you want a pure Java solution check out lambdaj
http://code.google.com/p/lambdaj/
Besides the possibility to define and use closure in a DSL-style, it also allows to manipulate collections in a functional way, without explicitly write closures or loops
Jambda is another FP-library. From the documentation:
Jambda is an attempt to provide the
Java(TM) world with tools and concepts
from functional programming (FP).
The goals are several:
To provide Java programmers with expressive FP constructs
To provide a bridge for Java programmers into the FP-world
To see how far Java and generics can be stretched
This
document is an attempt to introduce
Java programmers into the FP world,
and at the same time explain some (or
most) of the features in Jambda.
Apache Commons has some functional-ish code in it. See for example, the Predicate interface.
Google Guava has functional:
collection operations
concurrency constructs (Futures)
Or download OpenJDK 8 to try out Lambda expressions the way they will become in Java 8. Among others, the collection APIs are adjusted to support a functional style. See
http://macgyverdev.blogspot.se/2012/10/functional-programming-in-java.html
for examples of new collection APIs and comparisons with Guava, LambdaJ and FunctionalJava.
Scala was mentioned here, but there's a lot lighter and more Java compatible language: Xtend. It compiles to plain Java and uses the same type system. It has great Eclipse support. You can mix .java and .xtend files in a single project.
Sample code:
def static void main(String[] args) {
val s = #[1,2,3].map[it+43].join(", ")
println(s);
}
Although Functional Java is the most popular but i'll suggest you to try Google guava lib.
http://code.google.com/p/guava-libraries/
Related
We all know that one can use Java libraries from Scala and vice versa. But even looking over the surface of Java SE and Scala standard library, we can notice that there are many parts in them that solve identical or at least similar problems. The trivial examples are collections, concurrency and IO. I am not an expert in either of two, but I suspect that in general Java SE is broader in size while Scala SL contains more conceptually advanced features (such as actors). The question is, if we have access to both libraries and have an opportunity to use both languages, are there some recommendations when we should choose Java SE features over Scala SL?
In general, when writing in Scala, I would advise always using the Scala libraries over the Java ones. My advice on specific areas would be:
Collections - Scala's are much better, and I would always prefer them over the Java equivalents. Scala does however lack a mutable TreeMap, so if you need that sort of structure you'll have to go back to Java.
Concurrency - Scala's concurrency features wrap Java's and are more advanced. I'd always pick them.
IO - I think this is one area where Scala is narrower in what it supports. I would generally use a Scala Source when possible, but there may be more unusual situations where you'll have to drop back to Java IO (or possibly use a third party library).
Swing - Last time I looked, Scala's swing wrapping wasn't complete, so if you're doing a lot of Swing related stuff, you might take the decision to use Java's swing components everywhere for consistency.
Scala Libraries fit into two general categories:
Original Scala Libraries. These are entirely (or almost entirely) written in Scala. Usually, people will write libraries from scratch for good reasons. Maybe Java lacks a similar library, or maybe whoever wrote the Scala one thinks the Java equivalent has serious limitations.
Collections is one such example.
Scala Wrappers over Java Libraries. In these cases, Scala uses an adapter pattern (or one of the other similar patterns) to provide a Scala-friendly API. These APIs are more fluent, integrate well with important Scala classes (such as collections and Option), and often make use of powerful Scala features such as traits to decrease boilerplate.
These libraries rarely offer more functionality than what Java provides, but reduces boilerplate enormously and makes code using them more idiomatic. Often, however, they present just a subset of the total functionality provided by Java. Depending on the library, it may or may not be possible or easy to extend it by accessing the underlying Java classes.
Scala Swing is great example of these.
In the particular case of scala.io, that is not so much a library as a crude wrapper just to handle simple common scripting tasks with an idiomatic Scala API. It's adequate for that -- and certainly much kinder on my eyes than java.io --, but not for any serious I/O. There's a real I/O library for Scala currently undergoing evaluation for adoption.
Another example I like a lot if scala.sys.process. It wraps over Java's Process and ProcessBuilder, providing almost all of the functionality, and adding some. Furthermore, you can use most of Java internals if needed (the sole exception is Process itself, which isn't really much useful).
My advice is to use Scala libraries were they exist and fit your needs, extend them if they are mostly adequate, but reach for Java libraries without hesitation otherwise. After all, having a high degree of interoperability with Java is a key feature of Scala.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
I'm versed in Java, and starting to experiment with Groovy.
Because the two are integrated so well, I find myself writing in Java whatever I can because it's so easy. What specific tips can you offer that would speedup my work with Groovy?
Meaning - in what areas do groovy excel over java, and where should I stick to Java?
Some of the main things I like groovy for:
testing is probably the biggest win. The ability to change behavior at runtime and mock out methods is one of the greatest things about groovy. Convert your test suites to groovy now!
use the builders. Groovy builders have so much more expressiveness than traditional java. In particular, the MarkupBuilder for embedded snippets of XML or HTML is 1000s of times nicer to use than vanilla java
GPars if you're doing any sort of concurrent programming or threading
Also see Hidden features of Groovy and Why would one use Groovy over Java (note: was "removed from Stack Overflow for reasons of moderation").
Where I'd stick with java:
any place where speed really matters, stick with java. You still pay a high cost in performance for groovy's dynamic nature.
The problem with Groovy.
Groovy is a write-easy, but maintenance-nightmare. In my opinion, it should not be used in large projects. Inheriting somebody else's (or your own) code can be problematic, because very often you have no clue of the type of a variable, so you have your due diligence to find out, or use assertions to guarantee the incoming type to a method.
Groovy is a weak-typed language. The type of a variable is frequently ignored, or "conveniently" cast automatically, which leads to many bugs and slower performance.
Even the bests IDE's are lacking, because the practically typeless variables of the language. In many cases the compile just can't know what is the type of a variable. Even if you declare the type of a variable (which helps the editor to make suggestions), many programmers forget to define the variables type.
It has interesting ideas that I would love to see in Java, but stay away from it if your Groovy code will require more than a thousand lines.
* The answers in a nutshell *
Summarizing, here are the answers to both questions:
What specific tips can you offer that
would speedup my work with Groovy?
Use it only for small stuff. Otherwise, you will incur in technical-debt (see the Wikipedia). So far I'm in similar situation. Unit testing, using the console to test pieces of code, etc., are things that will speed up your development, since it's so easy to learn and use. Be sure to master closures, collections, and looping, and to understand what Java features are not available in Groovy.
Don't use pure Groovy for complex or large applications. In the long term the maintenance will slow you down.
Meaning - in what areas do groovy
excel over java, and where should I
stick to Java?
In a large or critical project you need to keep yourself disciplined and use dependable tools. It's like building a house: I are build a doll house, Groovy is fine :-) ... if it's not perfect, it's no biggie. If you build your own house or something bigger with little tolerance for error, you need to use quality tools and materials of better quality that don't let you oversee potential problems (Java, for example).
In any case, Groovy is like duck tape: some here and there may do no harm.
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 3 years ago.
Improve this question
I am a Java developer and I want to know how I can use Scala in my Java programs?
Go read Daniel Spiewak's excellent blog series about Scala. With Scala you can keep:
all your Java libraries
all the advantages of running on a JVM (ubiquity, administrative tools, profiling, garbage collection etc)
But you can write Scala code:
more concise and clear than Java (especially using more functional style, such as in the collections library)
it has closures and functions as part of the language
it has operator overloading (from the perspective of usage)
it has mixins (i.e. interfaces which contain implementation)
Also, take a look at this recent news item post on Scala's site:
"Research: Programming Style and Productivity".
In his paper, Gilles Dubochet, describes how he investigated two aspects of programming style using eye movement tracking. He found that it is, on average, 30% faster to comprehend algorithms that use for-comprehensions and maps, as in Scala, rather than those with the iterative while-loops of Java.
And another key quote from the news item:
Alex McGuire, who writes mission critical projects in Scala for power trading companies, says of Scala "The conciseness means I can see more of a program on one screen. You can get a much better overview. When I have some mathematical model to write with Java I have to keep two models in my head, the mathematical model itself and the second a model of how to implement it in Java. With Scala one model, the mathematical one, will do. Much more productive.”
You an read the rest of the post and other linked items there.
UPDATED 2019
I can name some simple points in plain language from my limited experience:
Properties. C++ and Java had this notion of a public getter/setter function "property" wrapped around an internal class variable which led to large amounts of boilerplate code. C# formalized this as a real language feature and reduced much of the boilerplate in C# 3.0 with auto-implemented properties. Scala classes define trivial properties simply as regular read only vals or read/write vars. The class may later choose to replace those with get or get/set methods without affecting client code. For this, Scala provides the most elegant solution with the least language features and complexity.
Arrays use regular generics. In Java/C#, int[] is redundant and confusing vs List<int> or List<Int>. Worse, in Java, List<Int> has lots of runtime overhead, so many developers have to know to use int[]. Scala avoids that problem. Also, in Java/C#, arrays support (covariant) casting, which was a mistake, that they now can't fix because of legacy concerns.
Scala has better support for immutability. val is a basic language feature.
Scala lets if blocks, for-yield loops, and code in braces return a value. This is very elegant in many situations. A very small plus is that this eliminates the need for a separate ternary operator.
Scala has singleton objects rather than C++/Java/C# class static. This is a cleaner solution.
Pattern matching. Object unpacking. Very nice in a large numbers of situations.
Native tuples.
"case classes" which are what most other languages would call record types or named tuples.
Fancier standard library with more elegant collections.
Multi-line strings. String interpolation formatting.
Optional semi-colons.
Cons.
Java has caught up a lot. Java 8 was first released in 2014, but it took several years for older Java versions to be phased out and the new Java 8 features to be fully used across the Java ecosystem. Now, lambdas and closures and basic functional collections, with support for filter/map/fold are quite standard for the Java ecosystem. More recently, Java has added basic var local variable type inference and has multi-line strings and switch expressions in release builds preview mode.
Scala is complicated. I'd highlight features like implicits to be inherently confusing.
Scala has minimal backward compatibility. Scala 2.10 artifacts are incompatible with Scala 2.11.
Building a Java API for other JVM-language developers like Scala or Clojure or Kotlin is normal, well supported and accepted. You generally don't want to build APIs in Scala that cater to non-Scala developers.
I am not sure you can easily use Scala in your Java programs, as in "call a Scala class from a Java class".
You can try, following the article "Mixing Java and Scala".
Relevant extracts:
The problem is that the Java and Scala compilation steps are separate: you can't compile both Java and Scala files in one go.
If none of your Java files reference any Scala classes you can first compile all your Java classes, then compile your Scala classes.
Or, if none of your Scala files reference any Java classes you can do it the other way around.
But if you want your Java classes to have access to your Scala classes and also have Scala classes have access to your Java classes, that's a problem.
Scala code can easily call directly into Java code, but sometimes calling Scala code from Java code is trickier, since the translation from Scala into bytecode is not quite as straightforward as for Java:
sometimes the Scala compiler adds characters to symbols or makes other changes that must be explicitly handled when calling from Java.
But a Scala class can implement a Java interface, and an instance of that class can be passed to a Java method expecting an instance of the interface.
The Java class then calls the interface methods on that instance exactly as if it were a Java class instance.
The opposite is possible, of course, as described in Roundup: Scala for Java Refugees, from Daniel Spiewak.
Scala or Java:
Pros:
Scala supports both functional and imperative OO programming styles and it advocates that both models are not conflicting with each other but yet they are orthogonal and can complement each other. Scala doesn't require or force the programmer to use a particular style, but usually the standard is to use functional style with immutable variables when appropriate (there are several benefits of using the functional approach such as concise and short syntax and using pure functions usually reduces the amount of non-determinism and side-effects from the code), while resorting to imperative programming when the code would look simpler or more understandable.
Scala doesn't require ; at the end of each line having it optional which leads to cleaner code
In Scala functions are first class cititzens
Scala supports some advanced features which are directly built in the language such as: Currying, Closures, Higher order functions, pattern matching, Higher Kinded Types, Monads, implicit params.
Scala can interact very well with Java and both can coexist. It is possible to use java libraries directly inside Scala code invoking Java classes from scala code.
Has Tuples built in the language which makes life easier in several scenarios
Supports operator overloading
has a rich Ecosystem and some popular open source projects in Apache are based on it.
Async and Non-blocking code is very easy to write with Scala Futures
Scala supports the Actor model using Akka which can be highly efficient and scalable when running distributed applications in multi-threaded and parallel business use cases (Enforce encapsulation without resorting to locks, State of actors is local and not shared, changes and data is propagated via message)
Code tends to be shorter if compared to Java (might not be always the case)
Cons:
Steep learning curve if compared to Java and other languages, requires more time in general from the learner to understand all the concepts clearly. Has many features
It is not as well established as Java in the market since it was invented later so Java in overall is more mature and more battle-tested.
Scala opens too many doors. It allows a lot of complex syntax that if used in a irresponsible way might lead to code that is hard to understand.
Abusing things such as operator overloading, implicit params and other constructs can be counter-productive and might ruin code legibility.
Java is also evolving and still getting better with newer versions (such as with JDK 9 modules)
Specially in comparison to C/C++ (which are declarative), how is Java imperative?
C/C++ is imperative too.
Edit: Imperative is do this, then do that, then do the next thing and so on. Declarative is, this are the rules, now what's the answer to this question. Google, you'll find plenty of info.
You are confusing the concepts, C and C++ are not declarative languages. Refer to Declarative Programming and Imperative Programming. Basically, with declarative languages (e.g. Prolog), you specifiy what you want to accomplish, without specifying how to accomplish it, which contrasts with imperative languages.
For future readers, although both Java and C/C++ are usually written imperatively,
Both languages support writing in a more declarative way for example by applying functional principles.
In the past years it has been more and more prominent and is encouraged by many influential software engineers such as Uncle Bob to go to a more functional (and thus declarative) approach.
In Java this was made much more easy with Java 8 that introduced Lambda, Streams etc.
I read this book about functional programming in Java and found it useful:
https://pragprog.com/book/vsjava8/functional-programming-in-java
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
What is the difference between Java and C++? Are both object-oriented?
This is far too general a question to be answered here.
Java is an explicitly object-oriented language, with the harder-to-use bits snipped off.
C++ is a multi-paradigm language with the safety off. You can do object-oriented programming in it, as well as procedural and generic.
If you had a more specific question, we could be of more help. Why did you ask? If you want recommendations for a particular platform, or project, or whatever, we could be more responsive.
A C++ programmer will tell you that Java is rubbish. A Java programmer will tell you that C++ is rubbish. Therefore I conclude that they are indeed the same thing.
Each language designed with different purposes in mind, so IMO it's not fair to compare the two from one perspective, and ignore the other.
Generally speaking, C++ is an open standard, designed for implementing high performance systems where speed and performance and critical, there are lots of impressing projects designed using this language like Phoenix Lander, Adobe Acrobat Reader and others. C++ gives the developer the ability to program using a very high level abstraction -using generics for example, and, when needed, go down deep to the bare metal of the machine -to handle an interrupt for instance.
Java was designed with other purposes in mind, when Sun was planning Oak (later called Java), it focused on web applications so it supported the language with a bunch of heavy libraries of easy-to-use interfaces considering that. and portability (Compile once, run anywhere) using JVM, which prevents the programmer from coding to specific machine, but instead coding to a sandbox which in turn runs the code on the hosting machine, and this has obviously negative reflections on performance/speed.
Comparison of those two language is a popular cause of debate between programmers, and this is due to their different working demands and nature, IMO every language has made mistakes in order to mature, for example, C++'s exported templates, and Java's lack of procedural programming (Big Mistake). plus, each one has its pros and cons regarding different aspects, hence the one that balance productivity/performance issue IS the right language.
For more information Wikipedia's comprehensive article on Comparison of Java and C++
It might be interesting to take a look at what languages are used (and being used) to create major systems (like Google) from here.
One of the most important differences hasn't been mentioned yet - one is compiled to machine code, the other is compiled to bytecode which is interpreted by a virtual machine.
Everything is Object in Java as everything is derived from java.lang.Object But this is not the case in C++
No pointers in Java whereas C++ has provide support for pointers
No destructors in java (Java has automatic garbage collection) but C++ has destructors to do that
Thread support is built in Java but not in C++
No scope resolution operator in Java
No Goto statement in Java
No Multiple Inheritance allowed in Java but C++ allows that
No operator overloading is allowed in Java but C++ allows that
Java is interpreted for most part and hence Platform independent
Both are object oriented but they are very different languages. This probably isn't the best forum to ask for the differences... I would suggest you look both up on Wikipedia and review the descriptions there. You will be able to see the differences very quickly for yourself.
I love c++ but unless you absolutely need to use c++ then use something else. When you need to use c++ then you will know the difference, Grasshopper.
(hint do not write device drivers, video decoders, encryption libraries, 3-d graphics engines or language run-time engines in java).
Yes, both are object oriented programming languages.
C++ is an evolution to C. Which was a system programming language. C++ Added many features to the language to make it object oriented. It became the mainstream programming language for that reason.
Java is an evolution of C++, with different goals ( cross platform for instance ). It remove some of the features that make C++ so hard to learn. Simplify others and remove others.
The main difference is C++ programs are compiled directly to machine code ( understood by the CPU ) while Java programs are compiled to be run in a "Virtual Machine" the JVM most of the cases. For these reasons java programs were interpreted by another program and at the beginning were veeeery slow programs. Nowadays the VM may optimize this code and make it run very very fast.
See this link.http://www.javacoffeebreak.com/articles/thinkinginjava/comparingc++andjava.html
Gross but accurate oversimplification: Java is easier. C++ is faster.
Just a quick addition to what David Thornley posted. C++ is a procedural language that supports Objects and OO design. Java is pure OO. Java does less but on more.