I have an ArrayList of Persons (name,surname,age). Now I'd like to clone just a subset of this ArrayList. Supposing I want to create from it a new ArrayList of Persons with age > 30.
It's not too complicated to set up an iteration which reads all attributes from Person and add it to the new ArrayList. However I just wonder if there's a more "elegant" and maybe more flexible too, way to achieve this, maybe implementing some interfaces I'm missing at the moment. Just one requirement: I'd like to stick to basic Java JDK API, it would be an overkill for this purpose to incorporate an external lib.
Thanks
Max

- 275
- 7
- 18
-
Thanks for all the comments, although I'll end up using a loop, I still have learnt something cool – Max Korn Oct 27 '12 at 16:49
4 Answers
I know you said you didn't want to use an external library, but if you did choose to, this snippet would help:
List<Person> persons = getSomePersons();
Collection<Person> greaterThan30 = Collections2.filter(persons, new Predicate<Person>() {
public boolean apply(Person person) {
return person.age > 30;
}
});
It requires the Guava Libraries. Basically it's a function that takes in a Predicate class with a type parameter. It has one method "apply" that returns the condition you want to accept.
This is one of the reasons people bemoan using Java. No proper higher-order function support. In Scala for example, you could do this:
val greaterThan30 = persons.filter(_.age > 30)

- 14,799
- 26
- 100
- 156
What you want is a filter, but there is no implementation of one in the Standard API library, and due to the lack of closures/lambdas, the implementations found in several third-party libraries such as lambdaj all have to be a bit more verbose than they would be in other languages. This will probably change in Java 8, though.
So just go ahead and do a loop - it's not as if there's something dirty about that, and even if there were a more elegant way, it would ultimately execute a loop as well.

- 342,105
- 78
- 482
- 720
That kind of operation is supposed to be using LINQ. However LINQ is not available in Java just yet. According to plan, it's gonna be in Java 8.
However before that arrives, try LambdaJ http://code.google.com/p/lambdaj/

- 3,420
- 4
- 36
- 70
-
-
I think LINQ is perhaps more than just closures. It's a DSL sitting over SQL, XML etc. – Brian Agnew Oct 28 '12 at 16:27
-
Agree that LINQ is more than just closures. But what I pointed in the link above is a feature that should solve the question asked. And it is part of LINQ. But yes, LINQ is more than just closure. – Wins Oct 29 '12 at 00:04
Collections.binarySearch
may do the trick for you.
Here you may find some examples of it. Implement binary search in objects

- 1
- 1

- 2,569
- 19
- 34
-
You should explain how exactly you want to make use of binary search. – jogojapan Oct 27 '12 at 13:30
-