Created
December 4, 2016 17:11
-
-
Save guangningyu/e9c648f6c46a2500d00faf1c553570d2 to your computer and use it in GitHub Desktop.
Reference: Functional Thinking Chapter 2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Java版本 | |
import java.util.List; | |
import java.util.ArrayList; | |
public class NameCleaner { | |
public static String cleanNames(List<String> listOfNames) { | |
StringBuilder result = new StringBuilder(); | |
for(int i = 0; i < listOfNames.size(); i++) { | |
if(listOfNames.get(i).length() > 1) { | |
result.append(capitalizeString(listOfNames.get(i))).append(","); | |
} | |
} | |
return result.substring(0, result.length() - 1).toString(); | |
} | |
public static String capitalizeString(String s) { | |
return s.substring(0, 1).toUpperCase() + s.substring(1, s.length()); | |
} | |
public static void main(String []args){ | |
List<String> names = new ArrayList<String>() {{ | |
add("jack"); | |
add("k"); | |
add("john"); | |
add("joe"); | |
}}; | |
System.out.println("The original names: " + names); | |
System.out.println("The cleaned names: " + cleanNames(names)); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Scala版本 | |
object NameCleaner { | |
def cleanNames(listOfNames : List[String]) : String = { | |
listOfNames | |
.filter(_.length > 1) | |
.map(_.capitalize) | |
.reduce(_ + "," + _) | |
} | |
def main(args : Array[String]) { | |
val names = List("jack", "k", "john", "joe"); | |
println("The original names: " + names); | |
println("The cleaned names: " + cleanNames(names)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment