Tsüklid

Python

Java

for i in range(10):
    print(i)
for (int i = 0; i < 10; i++) {
    System.out.println(i);
}

Või kasutades stream'i:

IntStream.range(0, 10).forEach(System.out::println);
i = 0
while i < 10:
    print(i)
    i += 1
int i = 0;
while (i < 10) {
    System.out.println(i++);
    // i++ -> prints out the current value
    // of i, then increments it by 1
}
lst = [1, 2, 3]
for x in lst:
    print(x)
List<Integer> list = new ArrayList<>();
list.add(1); list.add(2); list.add(3);
//List<Integer> list = new ArrayList<>(
//    Arrays.asList(1, 2, 3));
for (Integer x : list) {
    System.out.println(x);
}

Või kasutades stream'i:

List<Integer> list = new ArrayList<>(
        Arrays.asList(1, 2, 3)
);
list.stream().forEach(System.out::println);

Või kasutades listi enda forEach meetodit

List<Integer> list = Arrays.asList(1, 2, 3);
list.forEach(System.out::println);
for x in range(10, 0, -2):
    print(x)
for (int i = 10; i > 0; i -= 2) {
    System.out.println(i);
}

Või kasutades stream'i:

IntStream.iterate(10, n-> n -= 2)
        .takeWhile(n -> n > 0)
        .forEach(System.out::println);
j = 1
for i in range(11):
    print(j)
    j*=2
for (int i = 0, j = 1; i <= 10; j *= 2, i += 1) {
    System.out.println(j);
}
day = "Monday"
for letter in day:
    print(letter)
String day = "Monday";
for (int i = 0; i < day.length(); i++) {
    System.out.println(day.charAt(i));
}

Või kasutades stream'i:

String day = "Monday";
day.chars()
        .mapToObj(c -> (char)c)
        .forEach(System.out::println);

Paarisarvude summa

even_sum = 0
for x in range(10):
    if x % 2 == 0: even_sum += x

print(even_sum)

Või kasutades list comprehensionit:

print(sum([x for x in range(10) if x % 2 == 0]))
int evenSum = 0;
for (int i = 0; i < 10; i++) {
    if (i % 2 == 0) evenSum += i;
}
System.out.println(evenSum);

Või kasutades stream'i/lambdat:

System.out.println(
        IntStream.range(0, 10)
        .filter(x -> x % 2 == 0)
        .sum()
);

Sorteerimine ilma duplikaatideta

numbers = [3, 3, 1, 4, 7, 7, 7]
result = []
for n in numbers:
    if n not in result:
        result.append(n)

for nr in sorted(result):
    print(nr)

Või kasutades seti:

numbers = [3, 3, 1, 4, 7, 7, 7]
print(*sorted(set(numbers)), sep='\n')
List<Integer> numbers =
        Arrays.asList(3, 3, 1, 4, 7, 7, 7);
List<Integer> result = new ArrayList<>();
for (Integer n: numbers) {
    if (!result.contains(n)) {
        result.add(n);
    }
}
Collections.sort(result);
result.forEach(System.out::println);

Või kasutades stream'i/lambdat:

List<Integer> numbers = List.of(3, 3, 1, 4, 7, 7, 7);
numbers.stream()
    .distinct()
    .sorted()
    .forEach(System.out::println);

Loe tsüklite kohta siit: Tsükkel.