1 /* 2 * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. 8 * 9 * This code is distributed in the hope that it will be useful, but WITHOUT 10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 12 * version 2 for more details (a copy is included in the LICENSE file that 13 * accompanied this code). 14 * 15 * You should have received a copy of the GNU General Public License version 16 * 2 along with this work; if not, write to the Free Software Foundation, 17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 18 * 19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 20 * or visit www.oracle.com if you need additional information or have any 21 * questions. 22 */ 23 24 /* 25 * @test 26 * @summary Unit tests for String#transform(Function<String, R> f) 27 * @run main Transform 28 */ 29 30 package test.java.lang.String; 31 32 import java.util.function.Function; 33 import java.util.stream.Collectors; 34 35 public class Transform { main(String[] args)36 public static void main(String[] args) { 37 test1(); 38 } 39 40 /* 41 * Test String#transform(Function<? super String, ? extends R> f) functionality. 42 */ test1()43 static void test1() { 44 simpleTransform("toUpperCase", "abc", s -> s.toUpperCase()); 45 simpleTransform("toLowerCase", "ABC", s -> s.toLowerCase()); 46 simpleTransform("substring", "John Smith", s -> s.substring(0, 4)); 47 48 String multiline = " This is line one\n" + 49 " This is line two\n" + 50 " This is line three\n"; 51 String expected = "This is line one!\n" + 52 " This is line two!\n" + 53 " This is line three!\n"; 54 check("multiline", multiline.transform(string -> { 55 return string.lines() 56 .map(s -> s.transform(t -> t.substring(4) + "!")) 57 .collect(Collectors.joining("\n", "", "\n")); 58 }), expected); 59 } 60 simpleTransform(String test, String s, Function<String, String> f)61 static void simpleTransform(String test, String s, Function<String, String> f) { 62 check(test, s.transform(f), f.apply(s)); 63 } 64 check(String test, Object output, Object expected)65 static void check(String test, Object output, Object expected) { 66 if (output != expected && (output == null || !output.equals(expected))) { 67 System.err.println("Testing " + test + ": unexpected result"); 68 System.err.println("Output:"); 69 System.err.println(output); 70 System.err.println("Expected:"); 71 System.err.println(expected); 72 throw new RuntimeException(); 73 } 74 } 75 } 76