Swift SequenceとJava Stream mapメソッド

mapメソッド

Example 1

Java

IntStream stream = IntStream.of(0, 1, 2, 3, 4)
                            .map(x -> x * 2);
stream.forEach(System.out::println);

Swift

var mapNumbers = Range(0...4).map({x in x * 2})
print(mapNumbers)

Example 2

Java

String text = "This is Pen";
Stream<String> stream = Arrays.stream(text.split(" "))
                              .map(word -> word.toLowerCase());
stream.forEach(System.out::println);

Swift

var text = "This is Pen"
var mapStrings = text.split(separator: " ")
                     .map({word in word.lowercased()})
print(mapStrings)

Example 3

Java

List<String> words = List.of("ABCDE", "ABC", "ABCDEFGHI", "ABCDEF", "A");
Stream<Integer> stream = words.stream()
                              .map(word -> word.length());
stream.forEach(System.out::println);

Swift

var words = ["ABCDE", "ABC", "ABCDEFGHI", "ABCDEF", "A"]
var wordLengs = words.map({word in word.count})
print(wordLengs)

Java,Swift

Posted by shi-n