Tiếp theo phần 1 ở phần 2 chúng ta sẽ xem qua việc chuyển đổi các lệnh như for, switch giữa java và kotlin:
1.Switch / When
final int x = // value; final String xResult; switch (x){ case 0: case 11: xResult = "0 or 11"; break; case 1: case 2: //... case 10: xResult = "from 1 to 10"; break; default: if(x < 12 && x > 14) { xResult = "not from 12 to 14"; break; } if(isOdd(x)) { xResult = "is odd"; break; } xResult = "otherwise"; } final int y = // value; final String yResult; if(isNegative(y)){ yResult = "is Negative"; } else if(isZero(y)){ yResult = "is Zero"; }else if(isOdd(y)){ yResult = "is Odd"; }else { yResult = "otherwise"; }
val x = // value val xResult = when (x) { 0, 11 -> "0 or 11" in 1..10 -> "from 1 to 10" !in 12..14 -> "not from 12 to 14" else -> if (isOdd(x)) { "is odd" } else { "otherwise" } } val y = // value val yResult = when { isNegative(y) -> "is Negative" isZero(y) -> "is Zero" isOdd(y) -> "is odd" else -> "otherwise" }
2.Câu lệnh For
for (int i = 1; i < 11 ; i++) { } for (int i = 1; i < 11 ; i+=2) { } for (String item : collection) { } for (Map.Entry<String, String> entry: map.entrySet()) { }
for (i in 1 until 11) { } for (i in 1..10 step 2) {} for (item in collection) {} for ((index, item) in collection.withIndex()) {} for ((key, value) in map) {}
3.Collections (1)
final List<Integer> numbers = Arrays.asList(1, 2, 3); final Map<Integer, String> map = new HashMap<Integer, String>(); map.put(1, "One"); map.put(2, "Two"); map.put(3, "Three"); // Java 9 final List<Integer> numbers = List.of(1, 2, 3); final Map<Integer, String> map = Map.of(1, "One", 2, "Two", 3, "Three");
val numbers = listOf(1, 2, 3) val map = mapOf(1 to "One", 2 to "Two", 3 to "Three")
3.Collections (2)
for (int number : numbers) { System.out.println(number); } for (int number : numbers) { if(number > 5) { System.out.println(number); } }
numbers.forEach { println(it) } numbers.filter { it > 5 } .forEach { println(it) }
3.Collections(3)
final Map<String, List<Integer>> groups = new HashMap<>(); for (int number : numbers) { if((number & 1) == 0){ if(!groups.containsKey("even")){ groups.put("even", new ArrayList<>()); } groups.get("even").add(number); continue; } if(!groups.containsKey("odd")){ groups.put("odd", new ArrayList<>()); } groups.get("odd").add(number); }
val groups = numbers.groupBy { if (it and 1 == 0) "even" else "odd" }
3.Collections(4)
final List<Integer> evens = new ArrayList<>(); final List<Integer> odds = new ArrayList<>(); for (int number : numbers){ if ((number & 1) == 0) { evens.add(number); }else { odds.add(number); } }
val (evens, odds) = numbers.partition { it and 1 == 0 }
3.Collections(5)
final List<User> users = getUsers(); Collections.sort(users, new Comparator<User>(){ public int compare(User user, User otherUser){ return user.lastname.compareTo(otherUser.lastname); } }); // or users.sort(Comparator.comparing(user -> user.lastname));
val users = getUsers() users.sortedBy { it.lastname }