Intellij IDEA – in my opinion the most productive IDE for Java – comes with bunch of features helping getting rid of writing repetitive code – which is a everyday business no matter what language you use. One of them is live templates.

Live templates contain predefined code fragments. You can use them to insert frequently-used or custom code constructs into your source code file quickly, efficiently, and accurately.

IDEA comes with a set of live templates for Java, Maven, HTML, CSS and more and also enables to create custom templates.

Inserting live template

There are 2 ways to insert live template:

  1. Type live template abbreviation (for example dep) and next press TAB key
  2. Use shortcut Command + J (Mac) / Ctrl + J (PC) to popup list of available live templates in current context

At the beginning it’s quite difficult to remember all you wish to use and going back and forth from code to settings or browsing list is not very efficient – especially when you don’t know what you are looking for. That’s why I created gallery of (in my opinion) most useful built-in live templates for Java and Maven that can be used as a cheat sheet:

Maven

  • dep – Inserts <dependency/>

Code faster with Intellij IDEA live templates

  • pl – Inserts <plugin/>

Code faster with Intellij IDEA live templates

  • repo – Inserts <repo/>

Code faster with Intellij IDEA live templates

Iterations

  • fori – creates iteration loop

Code faster with Intellij IDEA live templates

  • itar – iterates elements of array

Code faster with Intellij IDEA live templates

  • itco – iterates elements of java.util.Collection

Code faster with Intellij IDEA live templates

  • iter – iterates Iterable

Code faster with Intellij IDEA live templates

  • itit – iterates java.util.Iterator

Code faster with Intellij IDEA live templates

  • itli – iterates elements of java.util.List

Code faster with Intellij IDEA live templates

Other

  • ifn – Inserts “if null” statement

Code faster with Intellij IDEA live templates

  • inn – Inserts “if not null” statement

Code faster with Intellij IDEA live templates

  • inst – Checks object type with instanceof and down-casts it

Code faster with Intellij IDEA live templates

  • lazy – Performs lazy initialization

Code faster with Intellij IDEA live templates

Plain

  • psf – public static final

Code faster with Intellij IDEA live templates

  • psfi – public static final int

Code faster with Intellij IDEA live templates

  • psfs – public static final String

Code faster with Intellij IDEA live templates

  • thr – throw new

Code faster with Intellij IDEA live templates

Summary

Using predefined Java templates is just a beginning. You can find ready to use templates for particular frameworks on Github and I really encourage you to create your custom, project specific ones.

If you created interesting common use live templates for Java or related frameworks feel invited to post them in comments.

相关文章: