2020-03-09

Lambda, Predicate


class Animal {
 boolean canHop = true;
 boolean canSwim;
 int x = 1;
 int y = 10;
}

interface CheckIface {
 int test1(Animal a);
}

//interface Predicate {
// boolean test(T t);
//}

class Solution {
 static final int i = 0;

 public static void main(String[] args) {
  Animal animal = new Animal();
  print1(animal, a -> {
   return a.x;
  });
  print1(animal, a -> a.y);
  print1(animal, a -> {
   return a.canHop ? 1 : 0;
  });

  print(animal, a -> a.canHop);
  print(animal, a -> a.canSwim);
 }

 static void print1(Animal a, CheckIface check) {
  if (check.test1(a) > 0)
   System.out.println("test " + check);
 }

 static void print(Animal a, Predicate<Animal> check) {
  if (check.test(a))
   System.out.println("test1 " + check);
 }

2020-03-06

Class StringBuilder

Modifier and Type Method and Description
StringBuilder append(boolean b)
StringBuilder append(char c)
StringBuilder append(char[] str)
StringBuilder append(char[] str, int offset, int len)
StringBuilder append(CharSequence s)
StringBuilder append(CharSequence s, int start, int end)
StringBuilder append(double d)
StringBuilder append(float f)
StringBuilder append(int i)
StringBuilder append(long lng)
StringBuilder append(Object obj)
StringBuilder append(String str)
StringBuilder append(StringBuffer sb)
StringBuilder appendCodePoint(int codePoint)
int capacity()
char charAt(int index)
int codePointAt(int index)
int codePointBefore(int index)
int codePointCount(int beginIndex, int endIndex)
StringBuilder delete(int start, int end)
StringBuilder deleteCharAt(int index)
void ensureCapacity(int minimumCapacity)
void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
int indexOf(String str)
int indexOf(String str, int fromIndex)
StringBuilder insert(int offset, boolean b)
StringBuilder insert(int offset, char c)
StringBuilder insert(int offset, char[] str)
StringBuilder insert(int index, char[] str, int offset, int len)
StringBuilder insert(int dstOffset, CharSequence s)
StringBuilder insert(int dstOffset, CharSequence s, int start, int end)
StringBuilder insert(int offset, double d)
StringBuilder insert(int offset, float f)
StringBuilder insert(int offset, int i)
StringBuilder insert(int offset, long l)
StringBuilder insert(int offset, Object obj)
StringBuilder insert(int offset, String str)
int lastIndexOf(String str)
int lastIndexOf(String str, int fromIndex)
int length()
int offsetByCodePoints(int index, int codePointOffset)
StringBuilder replace(int start, int end, String str)
StringBuilder reverse()
void setCharAt(int index, char ch)
void setLength(int newLength)
CharSequence subSequence(int start, int end)
String substring(int start)
String substring(int start, int end)
String toString()
void trimToSize()

Class String

Modifier and Type Method and Description
char charAt(int index)
int codePointAt(int index)
int codePointBefore(int index)
int codePointCount(int beginIndex, int endIndex)
int compareTo(String anotherString)
int compareToIgnoreCase(String str)
String concat(String str)
boolean contains(CharSequence s)
boolean contentEquals(CharSequence cs)
boolean contentEquals(StringBuffer sb)
static String copyValueOf(char[] data)
Equivalent to valueOf(char[]).
static String copyValueOf(char[] data, int offset, int count)
Equivalent to valueOf(char[], int, int).
boolean endsWith(String suffix)
boolean equals(Object anObject)
boolean equalsIgnoreCase(String anotherString)
static String format(Locale l, String format, Object... args)
Returns a formatted string using the specified locale, format string, and arguments.
static String format(String format, Object... args)
Returns a formatted string using the specified format string and arguments.
byte[] getBytes()
byte[] getBytes(Charset charset)
void getBytes(int srcBegin, int srcEnd, byte[] dst, int dstBegin)
Deprecated. 
This method does not properly convert characters into bytes. As of JDK 1.1, the preferred way to do this is via the getBytes() method, which uses the platform's default charset.
byte[] getBytes(String charsetName)
void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
int hashCode()
int indexOf(int ch)
int indexOf(int ch, int fromIndex)
int indexOf(String str)
int indexOf(String str, int fromIndex)
String intern()
boolean isEmpty()
static String join(CharSequence delimiter, CharSequence... elements)
static String join(CharSequence delimiter, Iterable<? extends CharSequence> elements)
int lastIndexOf(int ch)
int lastIndexOf(int ch, int fromIndex)
int lastIndexOf(String str)
int lastIndexOf(String str, int fromIndex)
int length()
boolean matches(String regex)
int offsetByCodePoints(int index, int codePointOffset)
boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len)
boolean regionMatches(int toffset, String other, int ooffset, int len)
String replace(char oldChar, char newChar)
String replace(CharSequence target, CharSequence replacement)
String replaceAll(String regex, String replacement)
String replaceFirst(String regex, String replacement)
String[] split(String regex)
String[] split(String regex, int limit)
boolean startsWith(String prefix)
boolean startsWith(String prefix, int toffset)
CharSequence subSequence(int beginIndex, int endIndex)
String substring(int beginIndex)
String substring(int beginIndex, int endIndex)
char[] toCharArray()
String toLowerCase()
String toLowerCase(Locale locale)
String toString()
String toUpperCase()
String toUpperCase(Locale locale)
String trim()
static String valueOf(boolean b)
Returns the string representation of the boolean argument.
static String valueOf(char c)
Returns the string representation of the char argument.
static String valueOf(char[] data)
Returns the string representation of the char array argument.
static String valueOf(char[] data, int offset, int count)
Returns the string representation of a specific subarray of the char array argument.
static String valueOf(double d)
Returns the string representation of the double argument.
static String valueOf(float f)
Returns the string representation of the float argument.
static String valueOf(int i)
Returns the string representation of the int argument.
static String valueOf(long l)
Returns the string representation of the long argument.
static String valueOf(Object obj)
Returns the string representation of the Object argument.

Interface List

All Known Implementing Classes:
AbstractList, AbstractSequentialList, ArrayList, AttributeList, CopyOnWriteArrayList, LinkedList, RoleList, RoleUnresolvedList, Stack, Vector
Class ArrayList
All Implemented Interfaces:
Serializable, Cloneable, Iterable, Collection, List, RandomAccess
Direct Known Subclasses:
AttributeList, RoleList, RoleUnresolvedList

Collections.sort(aList);
aList.sort(null);
A null value indicates that the elements' natural ordering should be used
aList.sort((e1,e2) -> e2 - e1); //DESC

boolean add(E e)
void add(int index, E element)
boolean addAll(Collection<? extends E> c)
boolean addAll(int index, Collection<? extends E> c)
void clear()
Object clone()
boolean contains(Object o)
void ensureCapacity(int minCapacity)
void forEach(Consumer<? super E> action)
E get(int index)
int indexOf(Object o)
boolean isEmpty()
Iterator<E> iterator()
int lastIndexOf(Object o)
ListIterator<E> listIterator()
ListIterator<E> listIterator(int index)
E remove(int index)
boolean remove(Object o)
boolean removeAll(Collection<?> c)
boolean removeIf(Predicate<? super E> filter)
protected void removeRange(int fromIndex, int toIndex)
void replaceAll(UnaryOperator<E> operator)
boolean retainAll(Collection<?> c)
E set(int index, E element)
int size()
void sort(Comparator<? super E> c)
Spliterator<E> spliterator()
List<E> subList(int fromIndex, int toIndex)
Object[] toArray()
<T> T[] toArray(T[] a)
void trimToSize()

Date & Time

https://docs.oracle.com/javase/tutorial/datetime/TOC.html

LocalDate today = LocalDate.now();
LocalDate dateOfBirth = LocalDate.of(2012, Month.MAY, 14);
LocalDate firstBirthday = dateOfBirth.plusYears(1); 
LocalTime thisSec;

for (;;) {
    thisSec = LocalTime.now();
    display(thisSec.getHour(), thisSec.getMinute(), thisSec.getSecond());
} 
 
System.out.printf("now: %s%n", LocalDateTime.now());

System.out.printf("Apr 15, 1994 @ 11:30am: %s%n",
                  LocalDateTime.of(1994, Month.APRIL, 15, 11, 30));

System.out.printf("now (from Instant): %s%n",
                  LocalDateTime.ofInstant(Instant.now(), ZoneId.systemDefault()));

System.out.printf("6 months from now: %s%n",
                  LocalDateTime.now().plusMonths(6));

System.out.printf("6 months ago: %s%n",
                  LocalDateTime.now().minusMonths(6));
 
DateTimeFormatter format = DateTimeFormatter.ofPattern("MMM d yyyy  hh:mm a");
LocalDateTime leaving = LocalDateTime.of(2013, Month.JULY, 20, 19, 30); 
 
LocalDate date = LocalDate.parse(in, DateTimeFormatter.BASIC_ISO_DATE);
    DateTimeFormatter formatter =
                      DateTimeFormatter.ofPattern("MMM d yyyy");
    LocalDate date = LocalDate.parse(input, formatter); 
Instant t1, t2;
...
long ns = Duration.between(t1, t2).toNanos();
 
Instant start;
...
Duration gap = Duration.ofSeconds(10);
Instant later = start.plus(gap);
LocalDate today = LocalDate.now();
LocalDate birthday = LocalDate.of(1960, Month.JANUARY, 1);

Period p = Period.between(birthday, today);
long p2 = ChronoUnit.DAYS.between(birthday, today);
System.out.println("You are " + p.getYears() + " years, " + p.getMonths() +
                   " months, and " + p.getDays() +
                   " days old. (" + p2 + " days total)");
The code produces output similar to the following:
You are 53 years, 4 months, and 29 days old. (19508 days total)
 
 

Prefix Method Type Use
of static factory Creates an instance where the factory is primarily validating the input parameters, not converting them.
from static factory Converts the input parameters to an instance of the target class, which may involve losing information from the input.
parse static factory Parses the input string to produce an instance of the target class.
format instance Uses the specified formatter to format the values in the temporal object to produce a string.
get instance Returns a part of the state of the target object.
is instance Queries the state of the target object.
with instance Returns a copy of the target object with one element changed; this is the immutable equivalent to a set method on a JavaBean.
plus instance Returns a copy of the target object with an amount of time added.
minus instance Returns a copy of the target object with an amount of time subtracted.
to instance Converts this object to another type.
at instance Combines this object with another.

 
 
https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html
 
All letters 'A' to 'Z' and 'a' to 'z' are reserved as pattern letters. The following pattern letters are defined:
  Symbol  Meaning                     Presentation      Examples
  ------  -------                     ------------      -------
   G       era                         text              AD; Anno Domini; A
   u       year                        year              2004; 04
   y       year-of-era                 year              2004; 04
   D       day-of-year                 number            189
   M/L     month-of-year               number/text       7; 07; Jul; July; J
   d       day-of-month                number            10

   Q/q     quarter-of-year             number/text       3; 03; Q3; 3rd quarter
   Y       week-based-year             year              1996; 96
   w       week-of-week-based-year     number            27
   W       week-of-month               number            4
   E       day-of-week                 text              Tue; Tuesday; T
   e/c     localized day-of-week       number/text       2; 02; Tue; Tuesday; T
   F       week-of-month               number            3

   a       am-pm-of-day                text              PM
   h       clock-hour-of-am-pm (1-12)  number            12
   K       hour-of-am-pm (0-11)        number            0
   k       clock-hour-of-am-pm (1-24)  number            0

   H       hour-of-day (0-23)          number            0
   m       minute-of-hour              number            30
   s       second-of-minute            number            55
   S       fraction-of-second          fraction          978
   A       milli-of-day                number            1234
   n       nano-of-second              number            987654321
   N       nano-of-day                 number            1234000000

   V       time-zone ID                zone-id           America/Los_Angeles; Z; -08:30
   z       time-zone name              zone-name         Pacific Standard Time; PST
   O       localized zone-offset       offset-O          GMT+8; GMT+08:00; UTC-08:00;
   X       zone-offset 'Z' for zero    offset-X          Z; -08; -0830; -08:30; -083015; -08:30:15;
   x       zone-offset                 offset-x          +0000; -08; -0830; -08:30; -083015; -08:30:15;
   Z       zone-offset                 offset-Z          +0000; -0800; -08:00;

   p       pad next                    pad modifier      1

   '       escape for text             delimiter
   ''      single quote                literal           '
   [       optional section start
   ]       optional section end
   #       reserved for future use
   {       reserved for future use
   }       reserved for future use