Skip to content

Generics Useful Imports

ychenxuan123 edited this page Apr 12, 2021 · 9 revisions

Useful Imports (with most common uses)

Arrays -> java.util.Arrays

  • use Arrays.sort to sort the primitive array after importing Arrays
  • use Arrays.asList(arrayName).stream() #convert array to a list before you can create stream.

ArrayList -> java.util.ArrayList

  • creates a mutable list of type E, common functions are add, get, remove, forEach, etc...
  • can be used with Comparator as well with method -> void sort(Comparator<? super E> c)

Comparable -> java.util.Comparable

  • override compareTo(method in Comparable), to affect the way items are sorted, for natural ordering

Comparator -> java.util.Comparator

  • override compare method, to compare two items of any class, allows comparison of two items of generic class

Collections -> java.util.Collections

  • used to implement Collections.sort methods to sort

HashMap -> java.util.HashMap

Map -> java.util.Map

  • acts like a dictionary in python
  • put method to put items in dictionary, get method to get value of a certain key
  • Try to use map interface when creating hashmaps, to enable flexible switching between maps in a code

function -> java.util.function

  • Predicate, Consumer, BiFunction

PriorityQueue -> java.util.PriorityQueue

Queue -> java.util.Queue

  • creates a queue of type E objects where you can use add, remove, or poll(removes and returns highest priority item) methods
  • can be used with Comparator as well, to make elements order w.r.t. the comparator passed in
  • Import Queue as well to use poll() or peek()! (useful in project)

Optionals - java.util.Optional

  • to use the optional class and methods in optionals

Streams - java.util.stream.Stream or java.util.stream.IntStream

  • IntStream is the primitive specialization of Stream, and includes more specific functions (.average(), .sum())
  • Convention is to start from a newline after every operation called

Note: Please help to add more useful imports or correct any mistakes :)