My Mac OSX custom Intellij shortcuts

Navigate: class cmd O, additional ctrl shift T
Navigate file: cmd shift O, added ctrl shift R (removed run context configuration)
Navigate declaration and usages, removed: cmd B, added: F3 (removed toggle bookmark)
Navigate type declaration, removed: shift + cmd B, added: shift + F3
Navigate implementations: cmd + I, ctrl + I, ctrl + shift + I
Navigate between matching braces: added ctrl + shift + [/]

Find usages: alt F7, added ctrl + shift + G (removed: unselect occurrences)

Find: cmd +F, added ctrl+ F (removed: right in editor actions)
Navigate File structure: cmd + F12, added ctrl + O (removed: override methods)

Refactor this: ctrl +T , added alt + shift + T (removed: switch task)
Rename: shift + F6, added alt + shift + R (removed: rerun tests)
Extract variable: alt+cmd+V, added alt + shift + L
Extract method: alt+cmd + M, added alt + shift + M
Duplicate line: added: alt + D (removed cmd+D)
Delete line: added: alt + shift + D
Hide all tool windows: shift + cmd + F12, added ctrl + M (removed: move caret to matching brace and commit message history)
Preferences: cmd + , added ctrl + alt + s
Show intention actions: alt + enter, added ctrl + 1 (Remove Go to bookmark 1)
Next highlighted error: F2, added ctrl+ . (removed: Choose lookup item and insert dot), added alt + .
Previous highlighted error: shift + F2, added ctrl+ , added alt + .
Reformat code: alt + cmd + L, added: ctrl + shift + F
Inline: added: alt + shift + I
Inline: alt + cmd + N, added alt + shift + I (removed: inspect code with editor settings)
Source code generate: cmd + N, ctrl + Enter, additionally: alt + shift + S
Extract field: alt + cmd + F, additionally alt + shift + F(removed: add to favorites)
Extract constant: alt + cmd + C, additionally: alt + shift + C (removed: recent changes)
**Extend/shrink selection: original: alt + up arrow/alt + down arrow changed to: alt + shift + arrow Up/Down, added additionally ctrl +W / ctrl + shift + W
Find in path: shift + cmd + F, added additionally: ctrl + alt + shift + F
Replace in path: shift + cmd + R, added additionally: ctrl + alt + shift + R
**Move line up: original: alt + shift + arrow Up/Down changed to: alt + arrow Up/Down
Organize imports: ctrl + alt + O, additionally: ctrl + shift + O, alt+shift+O
Navigate to Test/Junit (junit) added: ctrl + shift + J (removed: join lines), ctrl + shift + alt + T
Join lines: added: alt + shift + J (used also to compress/minify/linearize xml or json to single line)
Navigate type declaration: shift + cmd + B (removed shift + ctrl +B), added: shift + ctrl + D
Navigate declaration: added F3
Navigate Super method: added: ctrl + shift + U or added: ctrl + shift + M
Navigate bookmark show: added: shift + cmd + B, added: shift + ctrl + B, added: alt + shift + B, S
Bookmark add: added: cmd + B, added: ctrl + B, added: alt+ shift +B, A
Navigate bookmark menu: added ctrl + shift + alt + B, added alt+ shift +B, B (removed navigate type declaration)
Complete statement: ctrl + shift + Enter
Navigate to last edit location: ctrl + shift + backspace, added: cmd + L, added: ctrl + L
Navigate line number: ctrl + shift + L

** Rename: alt + shift + R (removed: rerun tests)

** Run/Debug context configuration original: run context configuration alt + shift + R,(removed: run/debug in main menu)

ctrl + R/D – run/debug junit test class opened in the editor
ctrl + alt + R/D – popup run/debug menu with classes/methods to select for running/debugging
ctrl + alt + cmd + R/D – rerun/debug class/method previously selected in the menu
alt + E – evaluate expression (in debug)
alt + shift + E – quick evaluate expression (in debug)

Added cmd+0, alt+0 terminal

Existing:
cmd + shift + T: navigate/create test
ctrl + Enter -> accept highlighted button in popup

VCS
Update: added cmd + U, added ctrl + U or added alt + shift + V, U
Diff: existing cmd + D (compare with local in vcs view)
Compare with same repository version: cmd+shift+D
Compare with local version: alt+shift+V, D
Compare with latest repo version: alt+shift+V, Shift+D

Prev/next difference: added ctrl + alt + ,/.
Push: existing alt + shift + K, or added: alt + P, or added: alt + shift + V, P
Revert: added alt + shift + V, R or added alt + R
History: added alt + H or added: alt + shift + H

Existing: View Parameter Info: cmd + P, added ctrl + P

Run: alt + shift + X, R
Run…: alt + shift + X, Shift + R
Debug: alt + shift + X, D
Debug…: alt + shift + X, Shift + D
Rerun tests: alt + shift + X, T
Rerun failed tests: alt + shift + X, Shift + T or alt + shift + X, F

Quick documentation: ctrl + Q
Navigate back/forward: added ctrl+alt+left/right arrow, added: alt+cmd+left/right arrow
Navigate Last edit location added: ctrl+shift+L
Navigate to line: cmd + L or added ctrl + L
Navigate bookmark: added ctrl + shift + B
Navigate to recently edited files: cmd + shift + E, ctrl + shift + E
Navigate to recent files: cmd + E, ctrl + E

Highlight usages in file: ctrl + F, ctrl + G

Generate source: added alt + shift + G
Find by action: added ctrl + shift + A
Ctrl + N added: new (Java, Scala)

Project Defaults -> Project Structure -> search sdk
Change color of ‘Identifier under caret’ to be brighter

Scala
Preferences-> Languages and Frameworks/Scala -> Show type info on mouse hover
Alt+Enter when cursor on valu/method -> Add type annotation to value definition
run scala console: cmd+shift+S

Advertisements

Java 8 Lambda returning lambda part 2

        Function<Integer, Function<Integer, Integer>> f = i1 -> i2 -> i1 - i2;
        List<Integer> ints = Arrays.asList(1, 2, 3);
        Integer res = 0;
        for (int ii = ints.size() - 1; ii >= 0; ii--) {
            Integer t = ints.get(ii); // 3 // 2 // 1
            Function<Integer, Integer> ff = f.apply(t); // i2 -> 3 - i2 // i2 -> 2 - i2 // i2 -> 1 - i2
            res = ff.apply(res); // 3 - 0 = 3 // 2 - 3 = -1 // 1 - -1 = 2
            System.out.println("intermediate res=" + res);
        }
        System.out.println("final res=" + res); // 2

Output:

intermediate res=3
intermediate res=-1
intermediate res=2
final res=2

Java 8 Lambda returning lambda

import java.util.Arrays;
import java.util.List;
import java.util.function.Function;
import java.util.function.Predicate;

public class LamdaReturningLambda {

    public static void main(String[] args) {
        List<String> strings = Arrays.asList("Bob", "Alice");

        // first approach
        strings
            .stream()
            .filter(e -> e.contains("i"))
            .filter(e -> e.contains("c"))
            .forEach(System.out::println);


        // second approach
        Predicate<String> contains_i = name -> name.contains("i");
        Predicate<String> contains_c = name -> name.contains("c");

        strings
            .stream()
            .filter(contains_i)
            .filter(contains_c)
            .forEach(System.out::println);


        // third approach
        strings
            .stream()
            .filter(containsString("i"))
            .filter(containsString("c"))
            .forEach(System.out::println);

        // fourth approach
        Function<String, Predicate<String>> containsFunc = s -> name -> name.contains(s); // lambda returning predicate
        strings
            .stream()
            .filter(containsFunc.apply("i"))
            .filter(containsFunc.apply("c"))
            .forEach(System.out::println);
    }

    static Predicate<String> containsString(String s) {
        return name -> name.contains(s);
    }

}

Output:

Alice
Alice
Alice
Alice

Java 8 jdk8 constructor reference

static class Person {
        private int id;

        public Person(int id) {
            this.id = id;
        }

        @Override
        public String toString() {
            return "Person{id=" + id + '}';
        }
    }

    public static void main(String[] args) {
        IntStream
                .range(0, 3)
                // .map(n -> new Person(n)) // does not compile since lambda return type is expected to be int
                .mapToObj(Person::new) // alternative to .mapToObj(n -> new Person(n))
                .forEach(System.out::println);
    }

Output:

Person{id=0}
Person{id=1}
Person{id=2}

Understanding java jdk8 Optional

        System.out.println( Optional.empty() ); // Optional.empty
        System.out.println( Optional.ofNullable(null) ); // Optional.empty
        System.out.println( Optional.ofNullable("a") ); // Optional[a]
        System.out.println( Optional.ofNullable("a").get() ); // a


        System.out.println( Optional.ofNullable("a").filter(s -> true) ); // Optional[a] (filter match)
        System.out.println( Optional.ofNullable("a").filter(s -> false) ); // Optional.empty (filter not match)

        System.out.println( Optional.ofNullable("a").map(s -> null)); // Optional.empty (mapper function returning null)
        System.out.println( Optional.ofNullable("a").map(s -> "b")); // Optional[b] (re-map)
        System.out.println( Optional.ofNullable("a").map(s -> "b".equals(s) ? s : null) ); // Optional.empty (filtering using map)
        System.out.println( Optional.ofNullable("a").map(s -> Optional.of("b")) ); // Optional[Optional[b]] (mapper function returning optional)
        System.out.println( Optional.empty().map(s -> { System.out.print("map"); return "b"; }) ); // Optional.empty (mapper not run)

        System.out.println( Optional.ofNullable("a").flatMap(s -> Optional.of("b")) ); // Optional[b] (mapper function returning optional)

        System.out.println( Optional.of("a").orElse("c") ); // a
        System.out.println( Optional.empty().orElse("c") ); // c


        System.out.println( Optional.ofNullable(null)
                .map(s -> printAndReturn("map: ", "b"))
                .orElse(printAndReturn("orElse: ", "c")) ); // orElse: c (executed only orElse branch, returned value c)

        System.out.println( Optional.of("a")
                                    .map(s -> printAndReturn("map: ", "b"))
                                    .orElse(printAndReturn("orElse: ", "c")) ); // map: orElse: b (executed both branches, returned value b)

        System.out.println( Optional.of("a")
                .map(s -> printAndReturn("map: ", "b"))
                .orElseGet(() -> printAndReturn("orElse: ", "c")) ); // map: b (executed only map branch, returned value b)

Hibernate n+1 selects and lazy loading vs eager

Assuming a shop can have many products we want to display shops along with products:
1) with one select query using join – we need to annotate in @OneToMany fetchType to EAGER to produce:

Hibernate:
select
this_.id as id1_1_1_,
this_.shipment_address as shipment2_1_1_,
products2_.shop_id as shop_id4_0_3_,
products2_.id as id1_0_3_,
products2_.id as id1_0_0_,
products2_.name as name2_0_0_,
products2_.price as price3_0_0_,
products2_.shop_id as shop_id4_0_0_
from
Shop this_
left outer join
Product products2_
on this_.id=products2_.shop_id

when calling

            Session session = sessionFactory.openSession();
            Criteria criteria = session.createCriteria(Shop.class).setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
            List list = criteria.list();

2) when we set fetch type to LAZY (default) then we get one select for shops and optionally additional selects for products for particular shop(s):

Hibernate:
select
this_.id as id1_1_0_,
this_.shipment_address as shipment2_1_0_
from
Shop this_

when retrieving shops
and when we want to retrieve products for particular shop(s)

            Shop shop = shops.get(0);
            List products = shop.getProducts();

then we get:

Hibernate:
select
products0_.shop_id as shop_id4_0_0_,
products0_.id as id1_0_0_,
products0_.id as id1_0_1_,
products0_.name as name2_0_1_,
products0_.price as price3_0_1_,
products0_.shop_id as shop_id4_0_1_
from
Product products0_
where
products0_.shop_id=?

for code

@Entity
public class Shop extends BaseEntity {

    @Column(name = "shipment_address", nullable = false)
    private String shipmentAddress;

    @OneToMany(mappedBy = "shop", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    private List products = new ArrayList<>();

    Shop() {
        // default constructor needed for ORM
    }

    public Shop(String shipmentAddress, Product... products) {
        this.shipmentAddress = shipmentAddress;
        for (Product product : products) {
            product.addShop(this);
            this.products.add(product);
        }
    }

    public List getProducts() {
        return products;
    }

    @Override
    public String toString() {
        return "Shop{" +
                super.toString() +
                ", shipmentAddress='" + shipmentAddress + '\'' +
                //", products=" + products +
                '}';
    }
}

@Entity
public class Product extends BaseEntity {

    @Column
    private String name;

    @Column
    private BigDecimal price;

    @ManyToOne
    @JoinColumn(name = "shop_id", foreignKey = @ForeignKey(name = "fk_product_shop"))
    private Shop shop;

    Product() {
        // default constructor needed for ORM
    }

    public Product(String name, BigDecimal price) {
        this.name = name;
        this.price = price;
    }

    void addShop(Shop shop) {
        this.shop = shop;
    }

    @Override
    public String toString() {
        return "Product{" +
                super.toString() +
                ", name='" + name + '\'' +
                ", price=" + price +
                ", shop.id=" + shop.getId() + '}';
    }
}