Generate methods in java

Java 8 Streams API – creating infinite streams with iterate and generate methods

Introduction – This tutorial explains how to create infinite streams using the Java 8 Stream API’s iterate() and generate() methods with examples to show their usage. This tutorial assumes that you are familiar with basics of Java 8 Streams API Read Basics of Java 8 Streams API .

Infinite Streams
Streams are different from collections although they can be created from collections. Unlike collections, a stream can go on generating/producing values forever. Java 8 Streams API provides two static methods in the Stream interface for creating infinite streams. These are Stream.iterate() and Stream.generate() .

Since infinite streams need to be limited to a finite number, based on specific requirement, hence it is a common practice to limit the number of elements produced by a stream using the Stream.limit() method.

Let us now take a look at how Stream.iterate() and Stream.generate() methods can be used to produce infinite streams.

Creating infinite Streams using the Stream.iterate() method
Let us start by looking at the signature of Stream.iterate() method –

Where,
– first input parameter is a seed value or initial value of type T
– second input parameter is a UnaryOperator function of type T
– output is a Stream of type T

Stream.iterate() method works just like a function-of algebraic operation which is commonly written as ƒ(x). The method first returns the seed-value itself. For the 2 nd element in the Stream it finds ƒ(seed-value) and from then on iteratively keeps applying function-of to the returned values.
So,
The 1 st value in the infinite Stream will be the seed-value
The 2 nd value will be ƒ(seed-value).
The 3 rd value will be ƒ(ƒ(seed-value))
The 4 th value will be ƒ(ƒ(ƒ(seed-value))) and so on

Let us take an example to understand how Stream.iterate() method works –
Suppose the UnaryOperator function fsqr() is a square function defined using the lambda expression – (Integer n) -> n*n and the seed is 2.
So,
The 1 st value returned in the infinite stream will be 2
The 2 nd value returned in the stream will be fsqr(2) OR 2*2=4.
The 3 rd value will be fsqr(fsqr(2)) i.e. fsqr(4) OR 4*4=16
The 4 th value will be fsqr(fsqr(fsqr(2))) i.e. fsqr(16) OR 16*16=256 and so on

Читайте также:  Python qt designer view code

The infinite stream will then have values – [2,4,16,256,… and so on…]

The Java code for using Stream.iterate() method to produce a Stream of iteratively squared values will be as below –

package com.javabrahman.java8.streams; import java.util.stream.Stream; public class InfiniteStreams < public static void main(String args[])< Stream.iterate(2, (Integer n) ->n*n) .limit(5) .forEach(System.out::println); > >
  • Seed passed as input to the Stream.iterate() method is 2 .
  • UnaryOperator function instance is passed using the lambda expression- (Integer n) -> n*n .
  • The output stream is limited to 5 elements using Stream.limit() method.
  • Output Stream is as expected with values – 2,4,16,256,65536 .

Creating infinite Streams using the Stream.generate() method
Stream.generate() method generates an infinite stream of elements by repeatedly invoking a Supplier Functional Interface Read tutorial on Supplier Functional Interface instance passed to it as an input parameter. Stream.generate() method’s signature looks like this –

Where,
– Only input is an instance of a Supplier Functional Interface of Type T
– Output is a Stream of type T

Let us now look at how to write the code to create an infinite stream containing random values using Stream.generate() and Math.random() methods.

package com.javabrahman.java8.streams; import java.util.stream.Stream; public class InfiniteStreams < public static void main(String args[]) < Stream.generate(Math::random) .limit(5) .forEach(System.out::println); >>
  • Math.random() method generates a random value between 0.0 and 1.0 every time it is called. The function descriptor Read tutorial on Java 8 Function Descriptors of Math.random() method matches that of the Supplier Functional Interface, so Math.random() is passed as an input to Stream.generate() method using its method reference Click to Read Tutorial on Java 8’s Method References – Math::random .
  • Stream.generate() method invokes Math.random() repeatedly to produce an infinite Stream of values between 0.0 and 1.0 .
  • The output stream is limited to 5 elements using Stream.limit() method.
  • Output Stream is as expected with 5 random values as shown above. .

Summary
In this tutorial we looked at what are infinite streams and how they can be generated using the static Stream.iterate() and Stream.generate() methods with Java 8 code examples to understand their usage.

Источник

Generating Code with IntelliJ IDEA

Helen Scott Logo

One of the super cool things about IntelliJ IDEA is how much code you can generate with minimum effort. Yes, it’s not the 1990s anymore, we’re no longer measured on how many lines of code we generate (thankfully), but you also know that Java has its fair share of boilerplate code.

Well, there’s a shortcut in IntelliJ IDEA that generates a lot of code for you:

Читайте также:  File put content python

These shortcuts load the Generate menu! Here’s a quick tour of where you can use it in Java projects in IntelliJ IDEA. It’s not a complete list; let me know where else we can use it please!

New Java Class

In the Project Window, you can use this shortcut to create a whole host of things which are project and folder specific. If you use the shortcut on your directory that is marked as your sources root (usually src) in a Java project you get the option to create a new Java file (among other things). You’re then asked to select between a Class, Interface, Record (Preview), Enum or Annotation. It’s a speedy way of creating new classes for your project.

Before we move on, a closely related shortcut is the one we use for a new Scratch File. It’s ⌘⇧N on macOS, or Ctrl+Shift+Alt+Ins on Windows/Linux. You can select to create a new Scratch file using ⌘N on macOS, or Alt+Ins on Windows and Linux in the Project Tool window, but it’s worth committing the scratch file shortcut to memory too as it’s handy to be able to dump some code or notes in an area outside your project and share it across IntelliJ IDEA projects.

Constructors

Now that you’ve got your class, you may want to generate a constructor or two. However, before we do that, let’s add a couple of variables to our class:

public class GenerateCode

We can use the same shortcut to make ourselves a constructor. We get some options here because we’ve got some fields in our class:

generate-constructor.png

public class GenerateCode < private final String name = "Helen"; private int age; private String mood; public GenerateCode(int age, String mood) < this.age = age; this.mood = mood; >>

Other Class-Based Generate Options

We don’t need to stop there either. There’s a whole host of code that IntelliJ IDEA can generate for us at this stage including:

  • Getter
  • Setter
  • Getter and Setter
  • equals() and hashCode()
  • toString()
  • Override Methods
  • Delegate Methods
  • Test

While we’re here, Java Records are coming and IntelliJ IDEA is ready. Another way you could generate code if you’re not ready to move to Java Records is to use the Generate shortcut to create a new Java record, and then you can convert the Java record to a normal Java class with ⌥⏎ on macOS, or Alt+Enter on Windows and Linux with your caret on the class name.

Читайте также:  Css fixed для div

Implement Methods

When our Java class implements an interface, we need to ensure that we implement that interface’s methods. The Generate menu helps us here too. Let’s say that our code looks like this, and we’re implementing NewInterface:

public class GenerateCode implements NewInterface

When we use ⌘N on macOS, or Alt+Ins on Windows and Linux this time, we see select a new option call Implement Methods:

implement-methods.png

Now IntelliJ IDEA has generated that code for us:

public class GenerateCode implements NewInterface < private final String name = "Helen"; private int age; private String mood; @Override public void doSomething() < >@Override public void goSomewhere() < >>

This also works for overriding methods from superclasses/super abstract classes.

Add Parameters / Arguments

Another useful trick you so is to use ⌘N on macOS, or Alt+Ins on Windows and Linux when you’re in a dialogue, and you need to add more rows or data. For example, we added a default constructor to our class, but we now want to refactor it to change the signature. Our code currently reflects the default constructor:

public class GenerateCode < private final String name = "Helen"; private int age; private String mood; public GenerateCode() < >>

Let’s refactor the Constructor with ⌘F6 on macOS, or Ctrl+F6 on Windows/Linux. In the Change Signature dialogue, you can use ⌘N on macOS, or Alt+Ins on Windows/Linux to add a new parameter. This saves you using your mouse to click the little + icon.

This trick works in all the dialogue boxes that require additional lines to be added that I’ve found so far.

Generate Test Methods

Finally, everyone loves a good test and rightly so. We’ve already mentioned that you can use the Generate menu from a Java method to generate a corresponding test class. However, once you’re in the test class, you can use ⌘N on macOS, or Alt+Ins on Windows and Linux again to create much of the boilerplate code you might need, including (for JUnit5 at least):

  • Test Method
  • SetUp Method
  • TearDown Method
  • BeforeClass Method
  • AfterClass Method

If you are working with a different testing framework, your Generate menu will give you other relevant options.

Summary

Java may be a little clunky on the boilerplate side of things, but IntelliJ IDEA takes the heavy lifting out of that to a large extent so along with the shorcut for intention actions, it’s a compelling combination.

Источник

Оцените статью