Java 8 Stream Cheatsheet

Convert Array To Map

List<Employment> employmentList = ....;
Map<String, Employment> employments =, Function.identity()));

Merge Lists without duplications

List<CustomerLabel> merged = new ArrayList<>(
                Stream.of(currentLabels, toAddCustomerLabel)
                                d -> d,
                                (CustomerLabel x, CustomerLabel y) -> x == null ? y : x))

Sum of a List

List<Sale> sales = ....
Double sum =, Double::sum);

Find Max Number

List<Double> numbers = ...
Double max =;

Find Min Number

List numbers = ...
Double min;

(continue updating … )

Regex Cheatsheet

CasesRegex (Java)
Valid Phone formatWith Parenthese:
^((\(\d{3}\))|\d{3})[- .]?\d{3}[- .]?\d{4}$
Example: (988) 989-8899

With International Prefix:
^(\+\d{1,3}( )?)?((\(\d{3}\))|\d{3})[- .]?\d{3}[- .]?\d{4}$
Example: +111 (202) 555-0125

10 digits:
^(\d{3}[- .]?){2}\d{4}$
Example: 989 999 6789
Valid Email format Simplest:

RFC 5322:

No leading, trailing, consecutive dots:
Valid Money format^(?:(?![,0-9]{14})\d{1,3}(?:,\d{3})*(?:\.\d{1,2})?|(?![.0-9]{14})\d{1,3}(?:\.\d{3})*(?:\,\d{1,2})?)$
Example: 123,234,432.43 , 123.234.432,43
Valid ISO Date time format(\d{4}-\d{2}-\d{2})[A-Z]+(\d{2}:\d{2}:\d{2}).([0-9+-:]+)
Example: 2021-10-12T23:59:00+07:00
Valid URL^(https?|ftp|file):\/\/[-a-zA-Z0-9+&@#\/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#\/%=~_|]
Strong password^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=])(?=\S+$).{8,}$

– A digit must occur at least once
– A lower case letter must occur at least once
– An upper case letter must occur at least once
– A special character must occur at least once
– No whitespace allowed in the entire string
– At least eight places
Valid IP v4^(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(\.(?!$)|$)){4}$
Valid IP v6Standard format:
Example: 2001:0db8:85a3:0000:0000:8a2e:0370:7334

Hex Compressed format:
Example: 2001:0db8:85a3:0000::8a2e:0370:7334
Valid Domain name^(?!-)[A-Za-z0-9-]+([\-\.]{1}[a-z0-9]+)*\.[A-Za-z]{2,6}$
Valid Credit Card Number^(?:4[0-9]{12}(?:[0-9]{3})?|[25][1-7][0-9]{14}|6(?:011|5[0-9][0-9])[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\d{3})\d{11})$

for Visa, MasterCard, American Express, Diners Club, Discover, and JCB cards.
Frequently used regular expressions


  • when use String regex = "copied regex", don’t forget to add extra "\" , so "\d" should become "\\d" , "\." become "\\.", etc
  • Replace ^ and $ as .* to have the “containing” matching. Example to match a string containing texts look like money :
    Boolean match = someString.match(".*(?:(?![,0-9]{14})\\d{1,3}(?:,\\d{3})*(?:\\.\\d{1,2})?|(?![.0-9]{14})\\d{1,3}(?:\\.\\d{3})*(?:\\,\\d{1,2})?).*")

Server Setup Cheatsheet

Users & Groups

Create User with password
useradd -m <username>
passwd <username>

Create a Group
groupadd <group name>

Add user to group
usermod -aG <group name> <username>

Remove user from group
deluser <username> <group name>


ssh <username>@<host IP or domain>
ssh -i <path to id_rsa file> <username>@<host IP or domain>

Generate SSH key

Add SSH public key to remote server
Manually paste public keys to: ~/.ssh/authorized_keys
Or: ssh-copy-id <username>@<ssh_host>
Note: Before ssh-copy-id, remote server must already create the underlying user. ssh-copy-id will prompt for password to login

Download files/folder via SSH
scp [-r] <username>@<remote server>:<path on remote server> <path on local>

Upload files via SSH
scp [-r] <path on local> <username>@<remote server>:<path on remote server>

Configure SSH timeout

vi /etc/ssh/sshd_config

# Hit "i" for INSERT mode on vi, edit below line
ClientAliveInterval  1200 # 1200 seconds

# Hit Esc to escape INSERT mode, type ":x" to save file
# Restart sshd
sudo systemctl reload sshd


List all Rules of all Chains:
iptables -n -L -v --line-numbers

List all Rules of a specific Chain
iptables -L INPUT --line-numbers

Delete a Rule in a Chain at a line number
iptables -D INPUT 10

Allow Incoming Traffic , Insert Rule add specific line
iptables -I INPUT <line_number> -p tcp --dport 80 -s <source_ip> -j ACCEPT

Allow Outgoing Traffic, Append Rule add end of a Chain
iptables -A OUTPUT -d <destination_ip> --sport <source port> -j ACCEPT

[NAT] Allow LAN nodes to access public network via interface eth0
iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE

[NAT] Redirect Incoming traffic to internal node
iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 80 -j DNAT --to

-p : tcp | udp | icmp | all

Run a script when startup

sudo vim /etc/rc.local

Edit the rc.local file with your desired commands like below :

# add your commands here
# last line must be exit 0 
exit 0

Then activate it by:

sudo chmod -v +x /etc/rc.local
sudo systemctl enable rc-local.service


Let the server notify you when something goes wrong !


apt-get install monit -y

Start as a daemon once per n seconds
monit -d 30

Configuration file
~/.monitrc or /etc/monitrc

Specify configuration file :
monit -c <path to cf file>

Configuration file sample content

Open Httpd for Dashboard

set httpd port 2812 allow username:password
# with IP
set httpd
     port 2812
     use address
     allow username:password
# using htpasswd file with limited username
set httpd port 2812
      allow md5 /etc/httpd/htpasswd john paul ringo george

Configure Daemon

SET DAEMON <seconds>

Setup Alert methods via Email

set alert
set mail-format {
      from: Monit Support <>
   subject: $SERVICE $EVENT at $DATE
   message: Monit $ACTION $SERVICE at $DATE on $HOST: $DESCRIPTION.
            Yours sincerely,
        [PORT number]
        [USERNAME string] [PASSWORD string]
        [using SSL [with options {...}]
        [CERTIFICATE CHECKSUM [MD5|SHA1] <hash>],

Setup Alert via Slack Webhook

  • Go to https://<yourteam>
  • Click Incoming WebHooks
  • Click Add Configuration
  • Select an existing channel or create a new one (e.g. #monit) – you can change it later
  • Click Add Incoming WebHooks integration
  • Copy the Webhook URL
  • Create file : touch /etc/ .
  • Sample script :
TEST_WHEN="`date +%Y-%m-%d_%H:%M:%S`"
SLACK_HOOK="Paste your Copied Slack web hook here"

curl -X POST --data-urlencode "payload={\"text\": \"$TEXT\"}" $SLACK_HOOK
  • Use in Configuration file
check program check-mysql ...
     if status != 0 then exec "/etc/ ServerName ServiceName OK"

Monitor ports with Alert via Slack Hook

check host ServerA with address localhost
 if failed port 5433 protocol pgsql with timeout 30 seconds
  then exec "/etc/ ServerA Postgresl FAIL"
   else if succeed exec "/etc/ ServerA Postgresl OK"

Monitor process with Alert via Email

check process mysqld with pidfile /var/run/
   if failed port 3306 protocol mysql then alert

Check remote host alive

check host Hostname with address
       if failed ping then alert

Check Disk amount usage

 check filesystem rootfs with path /
       if space usage > 90% then alert

Check Inode usage

 check filesystem rootfs with path /
       if inode usage > 90% then alert

Check CPU, Memory usage

check system $HOST
    if loadavg (5min) > 3 then alert
    if loadavg (15min) > 1 then alert
    if memory usage > 80% for 4 cycles then alert
    if swap usage > 20% for 4 cycles then alert
    # Test the user part of CPU usage 
    if cpu usage (user) > 80% for 2 cycles then alert
    # Test the system part of CPU usage 
    if cpu usage (system) > 20% for 2 cycles then alert
    # Test the i/o wait part of CPU usage 
    if cpu usage (wait) > 80% for 2 cycles then alert
    # Test CPU usage including user, system and wait. Note that 
    # multi-core systems can generate 100% per core
    # so total CPU usage can be more than 100%
    if cpu usage > 200% for 4 cycles then alert

Spring Annotation Cheatsheet

To create APIs

@Controller, @RestControllerDefine a Controller (in MVC)Spring MVC
@RequestMapping, @GetMapping, @PostMapping, @PutMapping, @DeleteMappingDefine APIsSpring MVC
@PathVariable, @RequestParam, @RequestBodyBind to parameters on the API’s URLSpring MVC
@ServiceDefine a Spring component to be @Autowired in ControllerSpring MVC
@RepositoryDefine a Spring component interacting with the database, usually be @Autowired inside @Service or @ControllerSpring MVC
@BeanDefine a custom Spring bean, usually to be @Autowired on other components, or to override some built-in beans provided by librariesSpring
@ConfigurationDefine a Spring bean, that stores configurations for particular libraries or for the application.Spring
@AutowiredCreate reference to another beans without manually creating constructorsSpring
@ControllerAdvice & @ExceptionHandlerCreate custom exception handlersSpring
Integer port;
Read values from application.propertiesSpring
Spring Web cheatsheet

To create database schema

Annotation & sample usagesFunctionVendor
class Company {… }
Create a table with name companyJPA/Hibernate
class User {…}
// “user” is a reserved keyword on Postgres
Create a table with name my_userJPA/Hibernate
@Id @GeneratedValue
Long companyId;
Define primary key with autogenerated idJPA/Hibernate
@GeneratedValueCreate a field that value is auto generated using shared sequence tableJPA/Hibernate
@GeneratedValue(strategy = GenerationType.IDENTITY)Create a field that value is auto generated using sequence table per [entity+column]JPA/Hibernate
String companyDescription;
Define column data typeJPA/Hibernate
@Column(columnDefinition=”boolean default true”)
Boolean active;
Define column data type and default valueJPA/Hibernate
@Column(name=”custom_column_name”)Specify column nameJPA/Hibernate
@Enumerated(EnumType.STRING)Tell hibernate to store enum value as String instead of ordinalJPA/Hibernate
Company employeeCompany;
Define Foreign key referencing to table companyJPA/Hibernate
UserProfile sampleUseProfile;
Foreign key field with 1:1 constraint. JPA/Hibernate
List<Address> sampleListAddress;
There will be a temporary table with 2 columns : company_id & address_idJPA/Hibernate
@OneToMany(fetch = FetchType.LAZY), @ManyToOne(fetch = FetchType.LAZY) , …To apply Lazy Loading technique to foreign key fieldsJPA/Hibernate
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
class ParentClass { … }

class ChildClass extend ParentClass { … }
There will be separated tables created for each child classes & parent classJPA/Hibernate
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
class ParentClass { … }
There will be only single table containing all columns of parent & child classesJPA/Hibernate
@Inheritance(strategy = InheritanceType.JOINED)
class ParentClass { … }
Each class has its table and querying a subclass entity requires joining the tablesJPA/Hibernate
List<String> sampleStringListField;
To store a List type field. There will be a temporary table created.JPA/Hibernate
public void beforeCreated() {…}
Method will be executed before a new entity is createdJPA/Hibernate
public void beforeUpdated(){…}
Method will be executed before an existing entity is updatedJPA/Hibernate
public void beforeDeleted() {…}
Method will be executed before an entity is about to removedJPA/Hibernate
public void afterCreated() {…}
Method will be executed after a new entity is createdJPA/Hibernate
public void afterUpdated() { … }
Method will be executed after an existing entity is updatedJPA/Hibernate
public void afterDeleted() {…}
Method will be executed after an entity is about to removedJPA/Hibernate
JPA/Hibernate Cheatsheet

To create Query

public interface UserRepository extends PagingAndSortingJpaRepository<User, Long> {
// Using Hibernate Query Language (HQL)
// auto generate query using method names
Optional<List<User>> findAllByActiveIsAndUsernameIs(Boolean active, String username);

// Using custom query
@Query("select c from Customer c where lower(concat(c.firstName, ' ', c.lastName)) like lower(concat(:q, '%') ) or lower(concat(c.firstName, ' ', c.middleName, ' ', c.lastName)) like lower(concat(:q, '%') )")
Optional<List<User>> search(@QueryParam String q);

// Join tables
@Query("select u,h from User u inner join House h on h.user_id = where h.address like lower(concat(:q, '%') )")
Optional<List<User>> searchByAddress(@QueryParam String q);


Annotation & sample usagesFunctionVendor
class UserDTO { … }
Generate no argument constructorLombok
class UserDTO { … }
Generate a constructor with all argumentsLombok
class UserDTO { … }
Generate getter & setter methodsLombok
class UserDTO { … }
Generate builderLombok
class UserDTO { … }
Generate builder , used for inheritance caseLombok
interface UserMapper {
public static UserMapper instance = Mappers.getClass(UserMapper.class)

Define a Mapper objectMapstruct
@Mapping(target=”field_a”, source=”field_b”, formatter=”formatterBeanName”)
@Mapping(source=”password”, ignore=true)
UserDTO fromUser(User user);

User fromDTO(UserDTO dto);
Configure Mapping of methods inside @MapperMapstruct
POJO code generating

Read custom configurations from

public class SettingProperties {
 String prop; 
 Long value;
 Boolean enabled;
 ....// ** standard getters & setters 
public class SettingConfig {
 SettingProperties settingProperties;
 public SettingConfig(SettingProperties props) {...}
setting.prop="Some text"

Async methods

public class SomeService {
 SomeRepository someRepository;
 public void someAsyncMethod(String param) {
 /// ... 


// to invoke

Cron job

@EnableScheduling // enable cron job support
public class CronJobConfig {
@Scheduled(fixedDelay = 1000)
public void scheduleFixedDelayTask() {
      "Fixed delay task - " + System.currentTimeMillis() / 1000);
public class ScheduledFixedRateExample {
    @Scheduled(fixedRate = 1000)
    public void scheduleFixedRateTaskAsync() throws InterruptedException {
          "Fixed rate task async - " + System.currentTimeMillis() / 1000);

@Scheduled(cron = "0 15 10 15 * ?")
public void scheduleTaskUsingCronExpression() {

    long now = System.currentTimeMillis() / 1000;
      "schedule tasks using cron jobs - " + now);