Java code readability and elegant

Wed, Feb 16, 2022 2-minute read

let your code more elegant

pass by value

public TreeNode search(TreeNode root, int target) {
    TreeNode cur = root;
    while (cur != null ) {
        if (root.key == target) {
            return root;
        } else if (root.key < target) {
            root = root.right;
        }else {
            root = root.left;
        }
    }
    return null;
}

java is passing by value, it won’t change the root value outside, thus you don’t need this code below

TreeNode cur = root;

jump out the while loop, root == null or root.key == target, just return root;

public TreeNode search(TreeNode root, int target) {
   
    while (root != null && root.key != target) {
   if (root.key < target) {
            root = root.right;
        }else {
            root = root.left;
        }
    }
    // root == null || root.key == target
    return root;
}

if else

if (a > 10) {
    b = b * 2;
} else {
    b = b * 3;
}
b = a > 10 ? b * 2 : b * 3;
Set<String> set1=new HashSet<>();
Set<String> set2=new HashSet<>();

if(flag){
    set1.add(id);
}else{
    set2.add(id);
} 
(flag? set1:set2).add(id);

filter

List<Integer> a = Lists.newArrayList<>();
for (int i = 0; i < 5; i++) {
    a.add(i);
}
List<Integer> b= Lists.newArrayList<>();
for (Integer num : a) {
    if (c.contains(num)) {
        b.add(num);
    }
}
List<Integer> a = Lists.newArrayList<>();
for (int i = 0; i < 5; i++) {
    a.add(i);
}
List<Integer> b= a.stream()
    .filter(c::contains)
    .collect(Collectors.toList());

Stream 优化 if 中判断条件过多情况

  • anyMatch:判断条件里任意一个满足条件,则返回 true;

  • allMatch:判断条件里所有都满足条件,则返回 true;

  • noneMatch:判断条件里所有都不满足条件,则返回 true;

List<String> list = Arrays.asList("a", "b", "c","d", "");
//任意一个字符串判断不为空则为true
boolean anyMatch = list.stream().anyMatch( s->StringUtils.isEmpty(s));
//所有字符串判断都不为空则为true
boolean allMatch = list.stream().allMatch( s->StringUtils.isEmpty(s));
//没有一个字符判断为空则为true
boolean noneMatch = list.stream().noneMatch( s->StringUtils.isEmpty(s));

 if(StringUtils.isEmpty(str1) || StringUtils.isEmpty(str2) ||
    StringUtils.isEmpty(str3) || StringUtils.isEmpty(str4) ||
    StringUtils.isEmpty(str5) || StringUtils.isEmpty(str6)
   ){
 .....
}

if (Stream.of(str1, str2, str3, str4, str5, str6).anyMatch(s -> StringUtils.isEmpty(s))) {
    ....
}

Enum

public enum dayEnum {
    Monday("aaa"),
    Tuesday("bbb"),
    Wednesday("ccc"),
    Thursday("ddd"),
    Sunday("eee");

    public String value;

    dayEnum(String value){
      this.value=value;
    }
}

public String getDay(String day) {
    return dayEnum.valueOf(day).value;
}

ImmutableMap

public String getDay(String day){
    if("Monday".equals(day)){
       return "aaa";
    }else if("Tuesday".equals(day)){
       return "bbb";
    }else if("Wednesday".equals(day)){
       return "ccc";
    }else if("Thursday".equals(day)){
       return "ddd";
    }else if("Sunday".equals(day)){
       return "eee";
    }else{
       ......
    }
}

public static final Map<String, String> dayMap = imutebleMap.<String, String>builder()
    .put("Monday", "äaa")
    .put("Tuesday", "bbb")
    .put("Wednesday", "ccc")
    .put("Thursday", "ddd")
    .put("Sunday", "eee")
    .build();

public String getDay(String day) {
    return dayMap.get(day);
}

Optional

String person = family.getAge().getName().getSex();

NullPointerException

String person = null;
if (famile != null) {
    ......
}

use Optional

String person = Optional.ofNullable(family)
    .flatMap(Family::getAge)
    .flatMap(Age::getName)
    .map(Name::getSex)
    .orElse(null);