Last active
October 8, 2016 14:20
-
-
Save dimitardanailov/ca88d2780ee7982449f834a09b424d28 to your computer and use it in GitHub Desktop.
Java imperative or functional
This file contains hidden or 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
public static boolean isPrimeFunctionalStyle(int number) { | |
return number > 1 && | |
IntStream.rangeClosed(2, (int) Math.sqrt(number)) | |
.noneMatch(i -> number % i == 0); | |
} |
This file contains hidden or 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
import java.util.ArrayList; | |
import java.util.List; | |
public class Lab1 { | |
/** | |
* Task: | |
* Given a collection of names, for example "Josh", "Bruce", "Nate", "Sara", "Neal", "Jackie", "Jane", "Barb". Write two methods. | |
* The first takes the collection, uses imperative style to total the number of characters in the names, and returns. | |
* The second method does the same thing but using declarative style. | |
* | |
* @param args | |
*/ | |
public static void main(String[] args) { | |
System.out.println("ImperativeStyle: " + imperativeStyle()); | |
System.out.println("DeclarativeStyle: " + declarativeStyle()); | |
} | |
public static int imperativeStyle() { | |
List<String> names = getCollection(); | |
int total = 0; | |
for (String name : names) { | |
total += name.length(); | |
} | |
return total; | |
} | |
public static int declarativeStyle() { | |
List<String> names = getCollection(); | |
return names | |
.stream() | |
.mapToInt(String::length) | |
.sum(); | |
} | |
public static List<String> getCollection() { | |
List<String> names = new ArrayList<>(); | |
names.add("Josh"); | |
names.add("David"); | |
names.add("George"); | |
return names; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment