On my way to Java 8

February 12, 2014 by Michael

This is a post where i want to collect some new expressions i’m learning on my way to Java 8. Hopefully i’ll keep updating it…

Use an IntStream to generate an Array with constant default values

// The "() -> 23" is a lambda that matches the functional interface of a Supplier 
// The the stream itself is infinite, but the array can certainly be not, so we must limit it
IntStream.generate(() -> 23).limit(42).toArray()

Use a similar construct to fill a list with constant values:

// The IntStream has a collect method that uses a supplier to instantiate a new target, 
// an accumulator to add to the new target and combiner to merge two targets to perform 
// a reduction of the given elements
IntStream.generate(() -> 23).limit(42).collect(ArrayList::new, ArrayList::add, ArrayList::addAll)

Use a range to zip elements of an indexable collection together:

List<Foobar> foobars = new ArrayList<>();
List<Double> differences = IntStream.range(1, foobars.size()) // create exclusive range
	.mapToObj(i -> { // map this to your result of pairwise combining elements
	    final Foobar left = foobars.get(i - 1);
	    return foobars.get(i).getAmount() - left.getAmount();
	}).collect(Collectors.toList()); // collect it in a list

Last update: 2014/02/12

No comments yet

Post a Comment

Your email is never published. We need your name and email address only for verifying a legitimate comment. For more information, a copy of your saved data or a request to delete any data under this address, please send a short notice to michael@simons.ac from the address you used to comment on this entry.
By entering and submitting a comment, wether with or without name or email address, you'll agree that all data you have entered including your IP address will be checked and stored for a limited time by Automattic Inc., 60 29th Street #343, San Francisco, CA 94110-4929, USA. only for the purpose of avoiding spam. You can deny further storage of your data by sending an email to support@wordpress.com, with subject “Deletion of Data stored by Akismet”.
Required fields are marked *