├── .gitignore ├── .travis.yml ├── LICENSE ├── README.md ├── pom.xml └── src ├── main └── java │ └── com │ └── nitorcreations │ ├── collections │ ├── NMaps.java │ └── NSets.java │ ├── predicates │ ├── NCollectionPredicates.java │ ├── NComparablePredicates.java │ ├── NOptionalPredicates.java │ ├── NPredicates.java │ └── NStringPredicates.java │ └── streams │ ├── NCollectors.java │ ├── NExtractors.java │ ├── NMappers.java │ └── NStreams.java └── test └── java └── com └── nitorcreations ├── collections ├── NMapsTest.java └── NSetsTest.java ├── predicates ├── NCollectionPredicatesTest.java ├── NComparablePredicatesTest.java ├── NOptionalPredicatesTest.java ├── NPredicatesTest.java └── NStringPredicatesTest.java ├── streams ├── Fixture.java ├── NCollectorsTest.java ├── NExtractorsTest.java ├── NMappersTest.java └── NStreamsTest.java └── test ├── Assertions.java ├── PredicateAssert.java └── TestUtils.java /.gitignore: -------------------------------------------------------------------------------- 1 | # Created by https://www.gitignore.io/api/intellij,java,maven 2 | 3 | ### Intellij ### 4 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio 5 | 6 | *.iml 7 | 8 | ## Directory-based project format: 9 | .idea/ 10 | # if you remove the above rule, at least ignore the following: 11 | 12 | # User-specific stuff: 13 | # .idea/workspace.xml 14 | # .idea/tasks.xml 15 | # .idea/dictionaries 16 | 17 | # Sensitive or high-churn files: 18 | # .idea/dataSources.ids 19 | # .idea/dataSources.xml 20 | # .idea/sqlDataSources.xml 21 | # .idea/dynamic.xml 22 | # .idea/uiDesigner.xml 23 | 24 | # Gradle: 25 | # .idea/gradle.xml 26 | # .idea/libraries 27 | 28 | # Mongo Explorer plugin: 29 | # .idea/mongoSettings.xml 30 | 31 | ## File-based project format: 32 | *.ipr 33 | *.iws 34 | 35 | ## Plugin-specific files: 36 | 37 | # IntelliJ 38 | /out/ 39 | 40 | # mpeltonen/sbt-idea plugin 41 | .idea_modules/ 42 | 43 | # JIRA plugin 44 | atlassian-ide-plugin.xml 45 | 46 | # Crashlytics plugin (for Android Studio and IntelliJ) 47 | com_crashlytics_export_strings.xml 48 | crashlytics.properties 49 | crashlytics-build.properties 50 | 51 | 52 | ### Java ### 53 | *.class 54 | 55 | # Mobile Tools for Java (J2ME) 56 | .mtj.tmp/ 57 | 58 | # Package Files # 59 | *.jar 60 | *.war 61 | *.ear 62 | 63 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 64 | hs_err_pid* 65 | 66 | 67 | ### Maven ### 68 | target/ 69 | pom.xml.tag 70 | pom.xml.releaseBackup 71 | pom.xml.versionsBackup 72 | pom.xml.next 73 | release.properties 74 | dependency-reduced-pom.xml 75 | buildNumber.properties 76 | .mvn/timing.properties 77 | 78 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: java 2 | jdk: 3 | - oraclejdk8 4 | sudo: false 5 | cache: 6 | directories: 7 | - $HOME/.m2 8 | script: 9 | - mvn verify javadoc:javadoc -B -V 10 | after_success: 11 | - mvn coveralls:report 12 | notifications: 13 | email: false 14 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright 2015- Nitor Creations Ltd. 2 | 3 | Licensed under the Apache License, Version 2.0 (the "License"); 4 | you may not use this file except in compliance with the License. 5 | You may obtain a copy of the License at 6 | 7 | http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | Unless required by applicable law or agreed to in writing, software 10 | distributed under the License is distributed on an "AS IS" BASIS, 11 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | See the License for the specific language governing permissions and 13 | limitations under the License. 14 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # java8-utils [![Build Status](https://travis-ci.org/NitorCreations/java8-utils.svg?branch=master)](https://travis-ci.org/NitorCreations/java8-utils) [![Coverage Status](https://coveralls.io/repos/NitorCreations/java8-utils/badge.svg?branch=master&service=github)](https://coveralls.io/github/NitorCreations/java8-utils?branch=master) [![Maven Central](https://img.shields.io/maven-central/v/com.nitorcreations/java8utils.svg)](http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22com.nitorcreations%22%20AND%20a%3A%22java8utils%22) 2 | 3 | The package provides helper methods for interacting with, e.g., the stream features of Java 8 and above. 4 | 5 | ### Maven 6 | 7 | 8 | com.nitorcreations 9 | java8utils 10 | 1.0.0 11 | 12 | 13 | ### Gradle 14 | 15 | compile 'com.nitorcreations:java8utils:1.0.0' 16 | 17 | ## Stream helpers 18 | 19 | Transforming to streams: 20 | 21 | NStreams.asStream(Optional) 22 | NStreams.asStream(Iterable) 23 | NStreams.asStream(Iterator) 24 | 25 | Concatenating multiple streams: 26 | 27 | NStreams.concat(Stream...) 28 | 29 | ### Collectors 30 | 31 | Collecting elements of streams: 32 | 33 | Map map = Stream.of(1, 1, 1, 3, 3, 6) 34 | .collect(NCollectors.countingOccurrences()); 35 | // {1=3, 3=2, 6=1} 36 | 37 | ## Predicates 38 | 39 | Common predicates include, e.g. 40 | 41 | NPredicates.is(T) // compare using == 42 | NPredicates.equalTo(T) // compare using #equals 43 | NPredicates.not(Predicate) // invert result of predicate 44 | ... 45 | NPredicates.having(Function, Predicate) // for matching, e.g., properties in a stream 46 | 47 | Example of `having` predicate usage: 48 | 49 | Stream.of("foo", "foobar", "barbar", "qux") 50 | .filter(s -> s.startsWith("f")) 51 | .filter(havingEqual(String::length, 3)) 52 | .collect(toList()); // -> List("foo") 53 | 54 | Includes predicates for collections, strings, and comparables: 55 | 56 | NCollectionPredicates: 57 | .empty() / .notEmpty() 58 | .contains(T) / .containsAll(T...) / .containsAny(T...) 59 | .doesNotContain()T / .doesNotContainsAllOf(T...) / .doesNotContainAnyOf(T...) 60 | 61 | Not forgetting the optionals: 62 | 63 | NOptionalPredicates 64 | .empty() / .present() 65 | .havingValue(T) / .havingValue(Predicate) 66 | .notHavingValue(T) / .notHavingValue(Predicate) 67 | 68 | 69 | ## Set helpers 70 | 71 | Helpers for creating sets: 72 | 73 | Set set = NSets.asSet(Iterable) 74 | Set set = NSets.asSet(Iterator) 75 | Set set = NSets.asSet(V...) 76 | 77 | ## Map helpers 78 | 79 | Helpers for creating map entries: 80 | 81 | Map.Entry entry = NMappers.entryOf("a", 1); 82 | 83 | Helpers for creating simple maps: 84 | 85 | NMaps.mapOfEntries(entryOf("a", 1), entryOf("c", 2), ...); 86 | NMaps.mapOf("a", 1, "c", 2, ...); // Up to ten entries 87 | NMaps.mapping(asList("a", "bee", "cheetah"), s -> s.length()); // Map from keys to values by function 88 | NMaps.mapOfLists(asList("a", "b", "c"), asList(1, 2, 3)); 89 | NMaps.combine(mapOf("a", 1), mapOf("b", 2, "c", 3)); 90 | 91 | ### Map entries as streams 92 | 93 | A stream of `Map.Entry` can be collected to a map by `NCollectors.entriesToMap()`: 94 | 95 | Stream> stream = ...; 96 | Map map = stream.collect(NCollectors.entriesToMap()); 97 | 98 | Combining entries on duplicate keys: 99 | 100 | Stream> stream = ...; 101 | Map stream.collect(NCollectors.entriesToMap((a, b) -> a+b); 102 | 103 | #### Consuming and mapping streams of entries 104 | 105 | Entries can be consumed and manipulated in a multitude of ways: 106 | 107 | // Just to show consumingEntry 108 | NMaps.mapOf("a", 1, "b", 2) 109 | .entrySet() 110 | .forEach(consumingEntry((key, val) -> System.out.printf("%s -> %d%n", key, val))); 111 | 112 | Further ways to manipulate entries in a stream: 113 | 114 | Map map = NMaps.mapOf("a", 1, "b", 2, "c", 3); 115 | final Map mapped = map.entrySet().stream() 116 | .map(NMappers.mappingKey((k, v) -> k + v)) 117 | .map(NMappers.mappingValue((k, v) -> v * v)) 118 | .collect(NCollectors.entriesToMap()); 119 | // Mapped now contains { "a1"=1; "b2"=4; "c3"=9 } 120 | 121 | ### Map extractors 122 | 123 | Helper methods for consuming maps: 124 | 125 | Stream keyStream = NExtractors.doWithKeys(Map map, Function fn); 126 | Stream valueStream = NExtractors.doWithValues(Map map, Function fn); 127 | 128 | Keys and values to sets or lists: 129 | 130 | NExtractors.extractKeysToSet(Map map, Function fn) 131 | NExtractors.extractKeysToList(Map map, Function fn) 132 | 133 | NExtractors.extractValuesToSet(Map map, Function fn) 134 | NExtractors.extractValuesToList(Map map, Function fn) 135 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | java8-utils 8 | The package provides helper methods for interacting with, e.g., the stream features of Java 8 and above. 9 | 10 | 2015 11 | 12 | com.nitorcreations 13 | java8utils 14 | 1.0.2-SNAPSHOT 15 | 16 | https://github.com/NitorCreations/java8-utils 17 | 18 | 19 | Reko Jokelainen 20 | reko.jokelainen@nitorcreations.com 21 | 22 | 23 | 24 | 25 | The Apache Software License, Version 2.0 26 | http://www.apache.org/licenses/LICENSE-2.0.txt 27 | repo 28 | 29 | 30 | 31 | scm:git:git@github.com:NitorCreations/java8-utils.git 32 | scm:git:git@github.com:NitorCreations/java8-utils.git 33 | https://github.com/NitorCreations/java8-utils 34 | HEAD 35 | 36 | 37 | https://github.com/NitorCreations/java8-utils/issues 38 | GitHub 39 | 40 | 41 | UTF-8 42 | 4.0.0 43 | Pf4aRjsZCJMfGqjSr5ZLww2ZwF9syaoSE 44 | 45 | 0.7.2.201409121644 46 | 47 | 48 | 49 | 50 | 51 | ossrh 52 | https://oss.sonatype.org/content/repositories/snapshots 53 | 54 | 55 | 56 | 57 | 58 | 59 | release 60 | 61 | 62 | 63 | org.apache.maven.plugins 64 | maven-source-plugin 65 | 66 | 67 | attach-sources 68 | 69 | jar-no-fork 70 | 71 | 72 | 73 | 74 | 75 | org.apache.maven.plugins 76 | maven-javadoc-plugin 77 | 78 | 79 | attach-javadocs 80 | 81 | jar 82 | 83 | 84 | 85 | 86 | 87 | org.apache.maven.plugins 88 | maven-gpg-plugin 89 | 1.6 90 | 91 | 92 | sign-artifacts 93 | verify 94 | 95 | sign 96 | 97 | 98 | ${gpg.keyname} 99 | ${gpg.keyname} 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | org.apache.maven.plugins 113 | maven-compiler-plugin 114 | 3.1 115 | 116 | 117 | 1.8 118 | 1.8 119 | 120 | 121 | 122 | org.apache.maven.plugins 123 | maven-javadoc-plugin 124 | 2.10.1 125 | 126 | 127 | org.sonatype.plugins 128 | nexus-staging-maven-plugin 129 | 1.6.6 130 | true 131 | 132 | ossrh 133 | https://oss.sonatype.org/ 134 | true 135 | 136 | 137 | 138 | org.eluder.coveralls 139 | coveralls-maven-plugin 140 | ${maven-plugin.coveralls.version} 141 | 142 | ${coveralls.token} 143 | 144 | 145 | 146 | org.jacoco 147 | jacoco-maven-plugin 148 | ${maven-plugin.jacoco.version} 149 | 150 | 151 | prepare-agent 152 | 153 | prepare-agent 154 | 155 | 156 | 157 | report 158 | 159 | report 160 | 161 | 162 | 163 | 164 | 165 | 166 | 167 | 168 | 169 | junit 170 | junit 171 | 4.12 172 | test 173 | 174 | 175 | org.assertj 176 | assertj-core 177 | 3.2.0 178 | test 179 | 180 | 181 | 182 | 183 | 184 | -------------------------------------------------------------------------------- /src/main/java/com/nitorcreations/collections/NMaps.java: -------------------------------------------------------------------------------- 1 | package com.nitorcreations.collections; 2 | 3 | import com.nitorcreations.streams.NCollectors; 4 | 5 | import java.util.*; 6 | import java.util.function.BinaryOperator; 7 | import java.util.function.Function; 8 | import java.util.stream.IntStream; 9 | 10 | import static com.nitorcreations.streams.NCollectors.entriesToMap; 11 | import static com.nitorcreations.streams.NMappers.entryOf; 12 | 13 | public final class NMaps { 14 | private NMaps() { /** prevent instantiation */} 15 | 16 | /** 17 | * Create a map of an arbitrary amount of map entries. Will throw exception on duplicate keys. 18 | * @param entries entries to collect to a map 19 | * @param the key type 20 | * @param the value type 21 | * @return the new map 22 | * @see NCollectors#entriesToMap() 23 | */ 24 | @SafeVarargs 25 | public static Map mapOfEntries(Map.Entry... entries) { 26 | return Arrays.stream(entries).collect(entriesToMap()); 27 | } 28 | 29 | /** 30 | * Create a map with keys mapped to values by the {@code valueFn}. The values are evaluated 31 | * eagerly and stored immediately. 32 | * 33 | * @param keys the keys to map 34 | * @param valueFn the function mapping keys to values 35 | * @param type of key 36 | * @param type of values 37 | * @return the map 38 | */ 39 | public static Map mapping(Set keys, Function valueFn) { 40 | return keys.stream() 41 | .map(k -> entryOf(k, valueFn.apply(k))) 42 | .collect(entriesToMap()); 43 | } 44 | 45 | /** 46 | * Create a map of the list of keys and list of values. Values are associated by the index 47 | * in the list. 48 | *

49 | * Will throw exception if sizes differ or either one is {@code null}. 50 | * 51 | * @param keys the keys of the map 52 | * @param values the values of the map 53 | * @param type of keys 54 | * @param type of values 55 | * @return the map containing the entries 56 | */ 57 | public static Map mapOfLists(List keys, List values) { 58 | if (keys.size() != values.size()) { 59 | throw new IllegalArgumentException(String.format("Keys and values sizes differ: %d != %d", keys.size(), values.size())); 60 | } 61 | return IntStream.range(0, keys.size()) 62 | .mapToObj(i -> entryOf(keys.get(i), values.get(i))) 63 | .collect(entriesToMap()); 64 | } 65 | 66 | /** 67 | * Combine multiple maps to a single one. Will throw exception on duplicate keys. 68 | * If duplicate values are expected, use {@link #combine(BinaryOperator, Map[])} 69 | * 70 | * @param maps the maps to combine 71 | * @param the key type 72 | * @param the value type 73 | * @return the resulting combined map 74 | */ 75 | public static Map combine(Map... maps) { 76 | return Arrays.stream(maps) 77 | .flatMap(m -> m.entrySet().stream()) 78 | .collect(entriesToMap()); 79 | } 80 | 81 | /** 82 | * Combine multiple maps to a single one. Uses {@code mergeFn} to cope with duplicate keys. 83 | * 84 | * @param maps the maps to combine 85 | * @param mergeFn the function to combine values on duplicate keys 86 | * @param the key type 87 | * @param the value type 88 | * @return the resulting combined map 89 | */ 90 | public static Map combine(BinaryOperator mergeFn, Map... maps) { 91 | return Arrays.stream(maps) 92 | .flatMap(m -> m.entrySet().stream()) 93 | .collect(entriesToMap(mergeFn)); 94 | } 95 | 96 | /** 97 | * Combine multiple maps to a single one. Uses the first encountered value as the value 98 | * on duplicate keys. 99 | * 100 | * @param maps the maps to combine 101 | * @param the key type 102 | * @param the value type 103 | * @return the resulting combined map 104 | */ 105 | public static Map combineAndSkip(Map... maps) { 106 | return combine((V v1, V v2) -> v1, maps); 107 | } 108 | 109 | /** 110 | * Create a map with the given values 111 | * @param k1 key 112 | * @param v1 value 113 | * @param type of key 114 | * @param type of value 115 | * @return the map 116 | */ 117 | public static Map mapOf(K k1, V v1) { 118 | return mapOfEntries(entryOf(k1, v1)); 119 | } 120 | 121 | /** 122 | * Create a map with the given values 123 | * @param k1 key 124 | * @param v1 value 125 | * @param k2 key 126 | * @param v2 value 127 | * @param type of key 128 | * @param type of value 129 | * @return the map 130 | */ 131 | public static Map mapOf(K k1, V v1, K k2, V v2) { 132 | return combine( 133 | mapOf(k1, v1), 134 | mapOf(k2, v2) 135 | ); 136 | } 137 | 138 | /** 139 | * 140 | * @param k1 key 141 | * @param v1 value 142 | * @param k2 key 143 | * @param v2 value 144 | * @param k3 key 145 | * @param v3 value 146 | * @param key type 147 | * @param value type 148 | * @return a map with the values 149 | */ 150 | public static Map mapOf(K k1, V v1, K k2, V v2, K k3, V v3) { 151 | return combine( 152 | mapOf(k1, v1), 153 | mapOf(k2, v2), 154 | mapOf(k3, v3) 155 | ); 156 | } 157 | 158 | /** 159 | * 160 | * @param k1 key 161 | * @param v1 value 162 | * @param k2 key 163 | * @param v2 value 164 | * @param k3 key 165 | * @param v3 value 166 | * @param k4 key 167 | * @param v4 value 168 | * @param key type 169 | * @param value type 170 | * @return a map with the values 171 | */ 172 | public static Map mapOf(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) { 173 | return combine( 174 | mapOf(k1, v1), 175 | mapOf(k2, v2), 176 | mapOf(k3, v3), 177 | mapOf(k4, v4) 178 | ); 179 | } 180 | 181 | /** 182 | * 183 | * @param k1 key 184 | * @param v1 value 185 | * @param k2 key 186 | * @param v2 value 187 | * @param k3 key 188 | * @param v3 value 189 | * @param k4 key 190 | * @param v4 value 191 | * @param k5 key 192 | * @param v5 value 193 | * @param key type 194 | * @param value type 195 | * @return a map with the values 196 | */ 197 | public static Map mapOf(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5) { 198 | return combine( 199 | mapOf(k1, v1), 200 | mapOf(k2, v2), 201 | mapOf(k3, v3), 202 | mapOf(k4, v4), 203 | mapOf(k5, v5) 204 | ); 205 | } 206 | 207 | /** 208 | * 209 | * @param k1 key 210 | * @param v1 value 211 | * @param k2 key 212 | * @param v2 value 213 | * @param k3 key 214 | * @param v3 value 215 | * @param k4 key 216 | * @param v4 value 217 | * @param k5 key 218 | * @param v5 value 219 | * @param k6 key 220 | * @param v6 value 221 | * @param key type 222 | * @param value type 223 | * @return a map with the values 224 | */ 225 | public static Map mapOf(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6) { 226 | return combine( 227 | mapOf(k1, v1), 228 | mapOf(k2, v2), 229 | mapOf(k3, v3), 230 | mapOf(k4, v4), 231 | mapOf(k5, v5), 232 | mapOf(k6, v6) 233 | ); 234 | } 235 | 236 | /** 237 | * 238 | * @param k1 key 239 | * @param v1 value 240 | * @param k2 key 241 | * @param v2 value 242 | * @param k3 key 243 | * @param v3 value 244 | * @param k4 key 245 | * @param v4 value 246 | * @param k5 key 247 | * @param v5 value 248 | * @param k6 key 249 | * @param v6 value 250 | * @param k7 key 251 | * @param v7 value 252 | * @param key type 253 | * @param value type 254 | * @return a map with the values 255 | */ 256 | public static Map mapOf(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6, K k7, V v7) { 257 | return combine( 258 | mapOf(k1, v1), 259 | mapOf(k2, v2), 260 | mapOf(k3, v3), 261 | mapOf(k4, v4), 262 | mapOf(k5, v5), 263 | mapOf(k6, v6), 264 | mapOf(k7, v7) 265 | ); 266 | } 267 | 268 | /** 269 | * 270 | * @param k1 key 271 | * @param v1 value 272 | * @param k2 key 273 | * @param v2 value 274 | * @param k3 key 275 | * @param v3 value 276 | * @param k4 key 277 | * @param v4 value 278 | * @param k5 key 279 | * @param v5 value 280 | * @param k6 key 281 | * @param v6 value 282 | * @param k7 key 283 | * @param v7 value 284 | * @param k8 key 285 | * @param v8 value 286 | * @param key type 287 | * @param value type 288 | * @return a map with the values 289 | */ 290 | public static Map mapOf(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6, K k7, V v7, K k8, V v8) { 291 | return combine( 292 | mapOf(k1, v1), 293 | mapOf(k2, v2), 294 | mapOf(k3, v3), 295 | mapOf(k4, v4), 296 | mapOf(k5, v5), 297 | mapOf(k6, v6), 298 | mapOf(k7, v7), 299 | mapOf(k8, v8) 300 | ); 301 | } 302 | 303 | /** 304 | * 305 | * @param k1 key 306 | * @param v1 value 307 | * @param k2 key 308 | * @param v2 value 309 | * @param k3 key 310 | * @param v3 value 311 | * @param k4 key 312 | * @param v4 value 313 | * @param k5 key 314 | * @param v5 value 315 | * @param k6 key 316 | * @param v6 value 317 | * @param k7 key 318 | * @param v7 value 319 | * @param k8 key 320 | * @param v8 value 321 | * @param k9 key 322 | * @param v9 value 323 | * @param key type 324 | * @param value type 325 | * @return a map with the values 326 | */ 327 | public static Map mapOf(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6, K k7, V v7, K k8, V v8, K k9, V v9) { 328 | return combine( 329 | mapOf(k1, v1), 330 | mapOf(k2, v2), 331 | mapOf(k3, v3), 332 | mapOf(k4, v4), 333 | mapOf(k5, v5), 334 | mapOf(k6, v6), 335 | mapOf(k7, v7), 336 | mapOf(k8, v8), 337 | mapOf(k9, v9) 338 | ); 339 | } 340 | 341 | /** 342 | * 343 | * @param k1 key 344 | * @param v1 value 345 | * @param k2 key 346 | * @param v2 value 347 | * @param k3 key 348 | * @param v3 value 349 | * @param k4 key 350 | * @param v4 value 351 | * @param k5 key 352 | * @param v5 value 353 | * @param k6 key 354 | * @param v6 value 355 | * @param k7 key 356 | * @param v7 value 357 | * @param k8 key 358 | * @param v8 value 359 | * @param k9 key 360 | * @param v9 value 361 | * @param k10 key 362 | * @param v10 value 363 | * @param key type 364 | * @param value type 365 | * @return a map with the values 366 | */ 367 | public static Map mapOf(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6, K k7, V v7, K k8, V v8, K k9, V v9, K k10, V v10) { 368 | return combine( 369 | mapOf(k1, v1), 370 | mapOf(k2, v2), 371 | mapOf(k3, v3), 372 | mapOf(k4, v4), 373 | mapOf(k5, v5), 374 | mapOf(k6, v6), 375 | mapOf(k7, v7), 376 | mapOf(k8, v8), 377 | mapOf(k9, v9), 378 | mapOf(k10, v10) 379 | ); 380 | } 381 | } 382 | -------------------------------------------------------------------------------- /src/main/java/com/nitorcreations/collections/NSets.java: -------------------------------------------------------------------------------- 1 | package com.nitorcreations.collections; 2 | 3 | import com.nitorcreations.streams.NStreams; 4 | 5 | import java.util.HashSet; 6 | import java.util.Iterator; 7 | import java.util.Set; 8 | 9 | import static java.util.Arrays.asList; 10 | import static java.util.stream.Collectors.toSet; 11 | 12 | public final class NSets { 13 | 14 | private NSets() { /** prevent instantiation */} 15 | 16 | /** 17 | * Create a new {@link HashSet} with the given values 18 | * 19 | * @param values the values to add to the set. 20 | * @param the type of the element 21 | * @return the set containing the values 22 | */ 23 | @SafeVarargs 24 | public static Set asSet(V... values) { 25 | return new HashSet<>(asList(values)); 26 | } 27 | 28 | /** 29 | * Create a new set with the values of the given iterable 30 | * 31 | * @param values the values to add to the set. 32 | * @param the type of the element 33 | * @return the set containing the values 34 | */ 35 | public static Set asSet(Iterable values) { 36 | return NStreams.asStream(values).collect(toSet()); 37 | } 38 | 39 | /** 40 | * Create a new set with the values of the given iterator 41 | * 42 | * @param iterator the values to add to the set. 43 | * @param the type of the element 44 | * @return the set containing the values 45 | */ 46 | public static Set asSet(Iterator iterator) { 47 | return asSet(() -> iterator); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/main/java/com/nitorcreations/predicates/NCollectionPredicates.java: -------------------------------------------------------------------------------- 1 | package com.nitorcreations.predicates; 2 | 3 | import java.util.Arrays; 4 | import java.util.function.Predicate; 5 | 6 | import static com.nitorcreations.predicates.NPredicates.*; 7 | import static com.nitorcreations.streams.NStreams.asStream; 8 | import static java.util.Arrays.asList; 9 | 10 | public final class NCollectionPredicates { 11 | private NCollectionPredicates() { /** prevent instantiation */} 12 | 13 | 14 | /** 15 | * Checks that the iterable is non-null and not empty 16 | * @param type of an element 17 | * @param type of the iterable 18 | * @return predicate 19 | */ 20 | public static > Predicate notEmpty() { 21 | return NPredicates.notNull().and(s -> s.iterator().hasNext()); 22 | } 23 | 24 | /** 25 | * Checks that the iterable is non-null and empty 26 | * @param type of an element 27 | * @param type of the iterable 28 | * @return predicate 29 | */ 30 | public static > Predicate empty() { 31 | return NPredicates.notNull().and(s -> !s.iterator().hasNext()); 32 | } 33 | 34 | /** 35 | * Checks that the iterable is non-null and contains target element (comparison by {@code #equals}) 36 | * @param type of an element 37 | * @param type of the iterable 38 | * @return predicate 39 | */ 40 | public static > Predicate contains(T element) { 41 | return NPredicates.notNull().and(it -> asStream(it).anyMatch(equalTo(element))); 42 | } 43 | 44 | /** 45 | * Checks that the iterable is non-null and contains all of the target elements (comparison by {@code #equals}) 46 | * @param type of an element 47 | * @param type of the iterable 48 | * @return predicate 49 | */ 50 | @SafeVarargs 51 | public static > Predicate containsAll(T... elements) { 52 | return containsAll(asList(elements)); 53 | } 54 | 55 | /** 56 | * Checks that the iterable is non-null and contains all of the target elements (comparison by {@code #equals}) 57 | * @param elements 58 | * @param type of an element 59 | * @param type of the iterable 60 | * @return predicate 61 | */ 62 | public static > Predicate containsAll(Iterable elements) { 63 | final Predicate allmatch = asStream(elements) 64 | .map(NCollectionPredicates::contains) 65 | .reduce(notEmpty(), (p1, p2) -> p1.and(p2)); 66 | return NPredicates.notNull().and(allmatch); 67 | } 68 | 69 | /** 70 | * Checks that the iterable is non-null and contains any of the target elements (comparison by {@code #equals}) 71 | * @param type of an element 72 | * @param type of the iterable 73 | * @return predicate 74 | */ 75 | @SafeVarargs 76 | public static > Predicate containsAny(T... elements) { 77 | return containsAny(asList(elements)); 78 | } 79 | 80 | /** 81 | * Checks that the iterable is non-null and contains any of the target elements (comparison by {@code #equals}) 82 | * @param elements 83 | * @param type of an element 84 | * @param type of the iterable 85 | * @return predicate 86 | */ 87 | public static > Predicate containsAny(Iterable elements) { 88 | final Predicate anyMatches = asStream(elements) 89 | .map(NCollectionPredicates::contains) 90 | .reduce(never(), (p1, p2) -> p1.or(p2)); 91 | return NPredicates.notNull().and(anyMatches); 92 | } 93 | 94 | /** 95 | * Checks that the iterable is non-null and does not contain the target element (comparison by {@code #equals}) 96 | * @param element the element 97 | * @param type of an element 98 | * @param type of the iterable 99 | * @return predicate 100 | */ 101 | public static > Predicate doesNotContain(T element) { 102 | return doesNotContainAnyOf(element); 103 | } 104 | 105 | /** 106 | * Checks that the iterable is non-null and contains none of target elements 107 | * @param elements elements 108 | * @param type of an element 109 | * @param type of the iterable 110 | * @return predicate 111 | */ 112 | @SafeVarargs 113 | public static > Predicate doesNotContainAnyOf(T... elements) { 114 | return doesNotContainAnyOf(Arrays.asList(elements)); 115 | } 116 | 117 | /** 118 | * Checks that the iterable is non-null and contains none of target elements 119 | * @param elements elements 120 | * @param type of an element 121 | * @param type of the iterable 122 | * @return predicate 123 | */ 124 | public static > Predicate doesNotContainAnyOf(Iterable elements) { 125 | return NPredicates.notNull().and(not(containsAny(elements))); 126 | } 127 | 128 | /** 129 | * Checks that iterable is non-null and does not contain all of the target elements. Will return {@code true} if some of the elements are present 130 | * 131 | * @param elements elements to find 132 | * @param type of an element 133 | * @param type of the iterable 134 | * @return predicate 135 | */ 136 | @SafeVarargs 137 | public static > Predicate doesNotContainAllOf(T... elements) { 138 | return doesNotContainAllOf(asList(elements)); 139 | } 140 | 141 | /** 142 | * Checks that iterable is non-null and does not contain all of the target elements. Will return {@code true} if some of the elements are present 143 | * 144 | * @param elements 145 | * @param type of an element 146 | * @param type of the iterable 147 | * @return predicate 148 | */ 149 | public static > Predicate doesNotContainAllOf(Iterable elements) { 150 | return NPredicates.notNull().and(not(containsAll(elements))); 151 | } 152 | } 153 | -------------------------------------------------------------------------------- /src/main/java/com/nitorcreations/predicates/NComparablePredicates.java: -------------------------------------------------------------------------------- 1 | package com.nitorcreations.predicates; 2 | 3 | import java.util.function.Predicate; 4 | 5 | public final class NComparablePredicates { 6 | 7 | private NComparablePredicates() { /** prevent instantiation */} 8 | 9 | /** 10 | * Matches when target is less than {@code other} 11 | * @param other the number to compare to 12 | * @param type of comparables 13 | * @return predicate 14 | */ 15 | public static Predicate> lt(T other) { 16 | return lessThan(other); 17 | } 18 | 19 | /** 20 | * Matches when target is less than or equal to {@code other} 21 | * @param other the number to compare to 22 | * @param type of comparables 23 | * @return predicate 24 | */ 25 | public static Predicate> lte(T other) { 26 | return lessThanOrEqualTo(other); 27 | } 28 | 29 | /** 30 | * Matches when target is less than {@code other} 31 | * @param other the number to compare to 32 | * @param type of comparables 33 | * @return predicate 34 | */ 35 | public static Predicate> lessThan(T other) { 36 | return a -> a.compareTo(other) < 0; 37 | } 38 | 39 | /** 40 | * Matches when target is less than or equal to {@code other} 41 | * @param other the number to compare to 42 | * @param type of comparables 43 | * @return predicate 44 | */ 45 | public static Predicate> lessThanOrEqualTo(T other) { 46 | return a -> a.compareTo(other) <= 0; 47 | } 48 | 49 | /** 50 | * Matches when target is greater than {@code other} 51 | * @param other the number to compare to 52 | * @param type of comparables 53 | * @return predicate 54 | */ 55 | public static Predicate> gt(T other) { 56 | return greaterThan(other); 57 | } 58 | 59 | /** 60 | * Matches when target is greater than or equal to {@code other} 61 | * @param other the number to compare to 62 | * @param type of comparables 63 | * @return predicate 64 | */ 65 | public static Predicate> gte(T other) { 66 | return greaterThanOrEqualTo(other); 67 | } 68 | 69 | /** 70 | * Matches when target is greater than {@code other} 71 | * @param other the number to compare to 72 | * @param type of comparables 73 | * @return predicate 74 | */ 75 | public static Predicate> greaterThan(T other) { 76 | return a -> a.compareTo(other) > 0; 77 | } 78 | 79 | /** 80 | * Matches when target is greater than or equal to {@code other} 81 | * @param other the number to compare to 82 | * @param type of comparables 83 | * @return predicate 84 | */ 85 | public static Predicate> greaterThanOrEqualTo(T other) { 86 | return a -> a.compareTo(other) >= 0; 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /src/main/java/com/nitorcreations/predicates/NOptionalPredicates.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015- Nitor Creations Ltd. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | * 16 | */ 17 | 18 | package com.nitorcreations.predicates; 19 | 20 | import java.util.Optional; 21 | import java.util.function.Predicate; 22 | 23 | import static com.nitorcreations.predicates.NPredicates.equalTo; 24 | import static com.nitorcreations.predicates.NPredicates.not; 25 | 26 | public final class NOptionalPredicates { 27 | private NOptionalPredicates() { /** prevent instantiation */} 28 | 29 | /** 30 | * Predicate that checks if optional is empty 31 | * @param type of containing optional 32 | * @return the predicate 33 | */ 34 | public static Predicate> empty() { 35 | return not(present()); 36 | } 37 | 38 | /** 39 | * Predicate that checks if optional is present 40 | * @param type of containing optional 41 | * @return the predicate 42 | */ 43 | public static Predicate> present() { 44 | return x -> x.isPresent(); 45 | } 46 | 47 | 48 | /** 49 | * Predicate that checks if value in optional matches target. 50 | * Returns {@code false} if value not present. 51 | * @param predicate the predicate to apply to the optional's contents 52 | * @param type of containing optional 53 | * @return the predicate 54 | */ 55 | public static Predicate> havingValue(Predicate predicate) { 56 | return NOptionalPredicates.present().and(o -> predicate.test(o.get())); 57 | } 58 | 59 | /** 60 | * Shorthand for {@code havingValue(equalTo(value))} 61 | * @param value the value to compare the contents to 62 | * @param type of containing optional 63 | * @return the predicate 64 | */ 65 | public static Predicate> havingValue(T value) { 66 | return havingValue(equalTo(value)); 67 | } 68 | 69 | /** 70 | * Shorthand for {@code havingValue(not(predicate))} 71 | * @param predicate the predicate to apply to the optional's contents 72 | * @param type of containing optional 73 | * @return the predicate 74 | */ 75 | public static Predicate> notHavingValue(Predicate predicate) { 76 | return havingValue(not(predicate)); 77 | } 78 | 79 | /** 80 | * Shorthand for {@code havingValue(not(equalTo(value)))} 81 | * @param value the value to compare the contents to 82 | * @param type of containing optional 83 | * @return the predicate 84 | */ 85 | public static Predicate> notHavingValue(T value) { 86 | return notHavingValue(equalTo(value)); 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /src/main/java/com/nitorcreations/predicates/NPredicates.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015- Nitor Creations Ltd. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | * 16 | */ 17 | 18 | package com.nitorcreations.predicates; 19 | 20 | import java.util.Objects; 21 | import java.util.function.Function; 22 | import java.util.function.Predicate; 23 | import java.util.stream.Stream; 24 | 25 | public final class NPredicates { 26 | private NPredicates() { /** prevent instantiation */} 27 | 28 | /** 29 | * Predicate that checks if {@code value == x} 30 | * @param value the value to compare to 31 | * @param type of value 32 | * @return predicate 33 | */ 34 | public static Predicate is(T value) { 35 | return x -> x == value; 36 | } 37 | 38 | /** 39 | * Predicate that checks {@code value.equals(x)} 40 | * @param value the value to compare to 41 | * @param type of value 42 | * @return predicate 43 | */ 44 | public static Predicate equalTo(T value) { 45 | return x -> Objects.equals(value, x); 46 | } 47 | 48 | /** 49 | * Predicate that inverts the result of target predicate. 50 | * @param predicate the predicate to invert 51 | * @param type of value 52 | * @return predicate 53 | */ 54 | public static Predicate not(Predicate predicate) { 55 | return x -> !predicate.test(x); 56 | } 57 | 58 | /** 59 | * Predicate that checks if {@code !(value == x)} 60 | * @param value the value to compare to 61 | * @param type of value 62 | * @return predicate 63 | */ 64 | public static Predicate not(T value) { 65 | return not(is(value)); 66 | } 67 | 68 | /** 69 | * Predicate that checks if {@code !value.equalTo(x)} 70 | * @param value the value to compare to 71 | * @param type of value 72 | * @return predicate 73 | */ 74 | public static Predicate notEqualTo(T value) { 75 | return not(equalTo(value)); 76 | } 77 | 78 | /** 79 | * Predicate that checks if {@code x == null} 80 | * @param type of value 81 | * @return predicate 82 | */ 83 | public static Predicate isNull() { 84 | return x -> x == null; 85 | } 86 | 87 | /** 88 | * Predicate that checks if {@code x != null} 89 | * @param type of value 90 | * @return predicate 91 | */ 92 | public static Predicate notNull() { 93 | return not(isNull()); 94 | } 95 | 96 | /** 97 | * Predicate that checks if {@code test} matches the result of {@code fn} 98 | * @param fn the fn that is applied to the element under test 99 | * @param test the predicate applied to the result of {@code fn} 100 | * @param source type 101 | * @param target type 102 | * @return predicate 103 | */ 104 | public static Predicate having(Function fn, Predicate test) { 105 | Objects.requireNonNull(fn, "fn must be supplied"); 106 | Objects.requireNonNull(test, "test must be supplied"); 107 | return x -> test.test(fn.apply(x)); 108 | } 109 | 110 | /** 111 | * Predicate that checks if {@code value} is equal to the result of {@code fn} 112 | * @param fn the fn that is applied to the element under test 113 | * @param value the value to compare to 114 | * @param source type 115 | * @param target type 116 | * @return predicate 117 | */ 118 | public static Predicate havingEqual(Function fn, S value) { 119 | Objects.requireNonNull(fn, "fn must be supplied"); 120 | return x -> equalTo(value).test(fn.apply(x)); 121 | } 122 | 123 | /** 124 | * Shorthand for {@code having(fn, equalTo(true))} 125 | * @param fn the fn that is applied to the element under test 126 | * @param source type 127 | * @return predicate 128 | * @see #having(Function, Predicate) 129 | * @see #equalTo(Object) 130 | */ 131 | public static Predicate having(Function fn) { 132 | return having(fn, equalTo(true)); 133 | } 134 | 135 | /** 136 | * Shorthand for {@code having(fn, equalTo(false))} 137 | * @param fn the fn that is applied to the element under test 138 | * @param source type 139 | * @return predicate 140 | * @see #having(Function, Predicate) 141 | * @see #equalTo(Object) 142 | */ 143 | public static Predicate notHaving(Function fn) { 144 | return having(fn, equalTo(false)); 145 | } 146 | 147 | 148 | /** 149 | * Matches all of target predicates. Similar to {@code p1.and(p2).and(p3)...} 150 | * @param preds predicates 151 | * @param type of predicate 152 | * @return predicate 153 | */ 154 | @SafeVarargs 155 | public static Predicate allOf(Predicate... preds) { 156 | arrayNotEmpty(preds); 157 | return Stream.of(preds).reduce(always(), (p1, p2) -> p1.and(p2)); 158 | } 159 | 160 | /** 161 | * Matches any of target predicates. Similar to {@code p1.or(p2).or(p3)...} 162 | * @param preds predicates 163 | * @param type of predicate 164 | * @return predicate 165 | */ 166 | @SafeVarargs 167 | public static Predicate anyOf(Predicate... preds) { 168 | arrayNotEmpty(preds); 169 | return Stream.of(preds).reduce(never(), (p1, p2) -> p1.or(p2)); 170 | } 171 | 172 | private static void arrayNotEmpty(T[] arr) { 173 | if (arr.length == 0) { 174 | throw new IllegalArgumentException("Empty list of predicates"); 175 | } 176 | } 177 | 178 | /** 179 | * Predicate that always returns {@code true} 180 | * @param type of predicate 181 | * @return predicate 182 | */ 183 | public static Predicate always() { 184 | return ignore -> true; 185 | } 186 | 187 | /** 188 | * Predicate that always returns {@code false} 189 | * @param type of predicate 190 | * @return predicate 191 | */ 192 | public static Predicate never() { 193 | return ignore -> false; 194 | } 195 | } 196 | -------------------------------------------------------------------------------- /src/main/java/com/nitorcreations/predicates/NStringPredicates.java: -------------------------------------------------------------------------------- 1 | package com.nitorcreations.predicates; 2 | 3 | import java.util.Objects; 4 | import java.util.function.Predicate; 5 | 6 | import static com.nitorcreations.predicates.NPredicates.not; 7 | import static com.nitorcreations.predicates.NPredicates.notNull; 8 | import static com.nitorcreations.streams.NStreams.asStream; 9 | import static java.util.Arrays.asList; 10 | 11 | public final class NStringPredicates { 12 | private NStringPredicates() { /** prevent instantiation */} 13 | 14 | /** 15 | * Null-safely check that the string starts with the prefix. The predicate returns {@code false} if 16 | * target is {@code null}. 17 | * 18 | * @param prefix the prefix to match 19 | * @return predicate 20 | */ 21 | public static Predicate startsWith(String prefix) { 22 | return NPredicates.notNull().and(s -> s.startsWith(prefix)); 23 | } 24 | 25 | /** 26 | * Null-safely check that the string ends with the suffix. The predicate returns {@code false} if 27 | * target is {@code null}. 28 | * 29 | * @param suffix the suffix to match 30 | * @return predicate 31 | */ 32 | public static Predicate endsWith(String suffix) { 33 | return NPredicates.notNull().and(s -> s.endsWith(suffix)); 34 | } 35 | 36 | /** 37 | * Check that the non-null string is either empty or contains only whitespace. The predicate returns {@code true} if 38 | * target is {@code null}. 39 | * 40 | * @return predicate 41 | */ 42 | public static Predicate isBlank() { 43 | return NPredicates.isNull().or(s -> s.trim().isEmpty()); 44 | } 45 | 46 | /** 47 | * Check that the non-null string is either empty or contains only whitespace. The predicate returns {@code false} if 48 | * target is {@code null}. 49 | * 50 | * @return predicate 51 | */ 52 | public static Predicate notBlank() { 53 | return not(isBlank()); 54 | } 55 | 56 | /** 57 | * Check that the non-null string contains the substring 58 | * 59 | * @param substring the string to find 60 | * @return predicate 61 | */ 62 | public static Predicate contains(String substring) { 63 | return containsAll(substring); 64 | } 65 | 66 | /** 67 | * Check that the non-null string contains all of the substrings in any order 68 | * 69 | * @param substring the strings to find 70 | * @return predicate 71 | */ 72 | public static Predicate containsAll(String... substring) { 73 | return containsAll(asList(substring)); 74 | } 75 | 76 | /** 77 | * Check that the non-null string contains all of the substrings in any order 78 | * 79 | * @return predicate 80 | * @param substrings 81 | */ 82 | public static Predicate containsAll(Iterable substrings) { 83 | return NPredicates. notNull() 84 | .and(s -> asStream(substrings) 85 | .filter(Objects::nonNull) 86 | .map(s::contains) 87 | .reduce(true, Boolean::logicalAnd)); 88 | } 89 | 90 | /** 91 | * Check that the non-null string contains any of the substrings 92 | * 93 | * @param substring the strings to find 94 | * @return predicate 95 | */ 96 | public static Predicate containsAny(String... substring) { 97 | return containsAny(asList(substring)); 98 | } 99 | 100 | /** 101 | * Check that the non-null string contains any of the substrings 102 | * 103 | * @return predicate 104 | * @param substrings 105 | */ 106 | public static Predicate containsAny(Iterable substrings) { 107 | return NPredicates. notNull() 108 | .and(s -> asStream(substrings) 109 | .filter(Objects::nonNull) 110 | .anyMatch(s::contains)); 111 | } 112 | 113 | /** 114 | * Check that the non-null string does not contain the substring. The predicate will return {@code false} 115 | * is target is {@code null} 116 | * 117 | * @param substring the string to find 118 | * @return predicate 119 | */ 120 | public static Predicate doesNotContain(String substring) { 121 | return doesNotContainAnyOf(substring); 122 | } 123 | 124 | /** 125 | * Check that the non-null string does not contain any of the the substrings. The predicate will return {@code false} 126 | * is target is {@code null} 127 | * 128 | * @param substring the string to find 129 | * @return predicate 130 | */ 131 | public static Predicate doesNotContainAnyOf(String... substring) { 132 | return doesNotContainAnyOf(asList(substring)); 133 | } 134 | 135 | /** 136 | * Check that the non-null string does not contain any of the the substrings. The predicate will return {@code false} 137 | * is target is {@code null} 138 | * 139 | * @return predicate 140 | * @param substrings 141 | */ 142 | public static Predicate doesNotContainAnyOf(Iterable substrings) { 143 | return not(containsAny(substrings)).and(notNull()); 144 | } 145 | 146 | /** 147 | * Check that the non-null string does not contain any of the the substrings. The predicate will return {@code false} 148 | * is target is {@code null} 149 | * 150 | * @param substring the string to find 151 | * @return predicate 152 | */ 153 | public static Predicate doesNotContainAllOf(String... substring) { 154 | return doesNotContainAllOf(asList(substring)); 155 | } 156 | 157 | /** 158 | * Check that the non-null string does not contain any of the the substrings. The predicate will return {@code false} 159 | * is target is {@code null} 160 | * 161 | * @return predicate 162 | * @param substrings 163 | */ 164 | public static Predicate doesNotContainAllOf(Iterable substrings) { 165 | return not(containsAll(substrings)).and(notNull()); 166 | } 167 | } 168 | -------------------------------------------------------------------------------- /src/main/java/com/nitorcreations/streams/NCollectors.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015- Nitor Creations Ltd. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | * 16 | */ 17 | 18 | package com.nitorcreations.streams; 19 | 20 | import java.util.Map; 21 | import java.util.function.BinaryOperator; 22 | import java.util.stream.Collector; 23 | 24 | import static java.util.function.Function.identity; 25 | import static java.util.stream.Collectors.counting; 26 | import static java.util.stream.Collectors.groupingBy; 27 | import static java.util.stream.Collectors.toMap; 28 | 29 | public final class NCollectors { 30 | private NCollectors() { /** prevent instantiation */} 31 | 32 | /** 33 | * Counts occurrences of different elements in the stream 34 | * @param type of a single element in the stream 35 | * @return collector 36 | */ 37 | public static Collector> countingOccurrences() { 38 | return groupingBy(identity(), counting()); 39 | } 40 | 41 | /** 42 | * NOTE: will throw exception on duplicate keys. See {@link #entriesToMap(BinaryOperator)} to 43 | * cope with this. 44 | * @param key 45 | * @param val 46 | * @return collector 47 | * @see #entriesToMap(BinaryOperator) 48 | */ 49 | public static Collector, ?, Map> entriesToMap() { 50 | return toMap( 51 | entry -> entry.getKey(), 52 | entry -> entry.getValue() 53 | ); 54 | } 55 | 56 | /** 57 | * Collect a stream of entries to a map. Uses {@code mergeFn} to decide what to do on duplicate keys. 58 | * If duplicate keys are not expected, you can use {@link #entriesToMap()} 59 | * @param mergeFn the function to merge values for duplicate keys. 60 | * @param key 61 | * @param val 62 | * @return collector 63 | */ 64 | public static Collector, ?, Map> entriesToMap(BinaryOperator mergeFn) { 65 | return toMap( 66 | entry -> entry.getKey(), 67 | entry -> entry.getValue(), 68 | mergeFn 69 | ); 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /src/main/java/com/nitorcreations/streams/NExtractors.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015- Nitor Creations Ltd. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | * 16 | */ 17 | 18 | package com.nitorcreations.streams; 19 | 20 | import java.util.List; 21 | import java.util.Map; 22 | import java.util.Set; 23 | import java.util.function.Function; 24 | import java.util.stream.Stream; 25 | 26 | import static java.util.stream.Collectors.toList; 27 | import static java.util.stream.Collectors.toSet; 28 | 29 | public final class NExtractors { 30 | private NExtractors() { /** prevent instantiation */} 31 | 32 | public static Stream doWithKeys(Map map, Function fn) { 33 | return map.keySet().stream().map(fn); 34 | } 35 | 36 | public static Set extractKeysToSet(Map map, Function fn) { 37 | return doWithKeys(map, fn).collect(toSet()); 38 | } 39 | 40 | public static List extractKeysToList(Map map, Function fn) { 41 | return doWithKeys(map, fn).collect(toList()); 42 | } 43 | 44 | public static Stream doWithValues(Map map, Function fn) { 45 | return map.values().stream().map(fn); 46 | } 47 | 48 | public static Set extractValuesToSet(Map map, Function fn) { 49 | return doWithValues(map, fn).collect(toSet()); 50 | } 51 | 52 | public static List extractValuesToList(Map map, Function fn) { 53 | return doWithValues(map, fn).collect(toList()); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/main/java/com/nitorcreations/streams/NMappers.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015- Nitor Creations Ltd. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | * 16 | */ 17 | 18 | package com.nitorcreations.streams; 19 | 20 | import java.util.AbstractMap; 21 | import java.util.Map; 22 | import java.util.function.BiConsumer; 23 | import java.util.function.BiFunction; 24 | import java.util.function.Consumer; 25 | import java.util.function.Function; 26 | 27 | public final class NMappers { 28 | private NMappers() { /** prevent instantiation */} 29 | 30 | /** 31 | * A function to map the values of an {@link java.util.Map.Entry} and return the modified entry. Provides the key to the mapper function as a convenience. 32 | *

33 | * Example: 34 | *

{@code
 35 |      *   Map map = singletonMap("foo", 1); // Or whatever
 36 |      *   Map mapped = map.entrySet().stream()
 37 |      *                                   .map(mappingValue((key, value) -> "Value was: " + value))
 38 |      *                                   .collect(entriesToMap());
 39 |      * }
40 | * 41 | * @param mapper the mapping function for the values 42 | * @param key type, will not change 43 | * @param value source type 44 | * @param value target type 45 | * @return a mapper from entry to entry 46 | */ 47 | public static Function, Map.Entry> mappingValue(BiFunction mapper) { 48 | return entry -> entryOf(entry.getKey(), mapper.apply(entry.getKey(), entry.getValue())); 49 | } 50 | 51 | /** 52 | * A function to map the keys of an {@link java.util.Map.Entry} and return the modified entry. Provides the value to the mapper function as a convenience 53 | *

54 | * Example: 55 | *

{@code
 56 |      *   Map map = singletonMap("foo", 1); // Or whatever
 57 |      *   Map mapped = map.entrySet().stream()
 58 |      *                                     .map(mappingKey((key, value) -> key.length()))
 59 |      *                                     .collect(NCollectors.entriesToMap());
 60 |      * }
61 | * 62 | * @param mapper the mapping function for the values 63 | * @param key source type 64 | * @param value type, will not change 65 | * @param key target type 66 | * @return a mapper from entry to entry 67 | */ 68 | public static Function, Map.Entry> mappingKey(BiFunction mapper) { 69 | return entry -> entryOf(mapper.apply(entry.getKey(), entry.getValue()), entry.getValue()); 70 | } 71 | 72 | /** 73 | * A function to map the entries to any type. 74 | *

75 | * Example: 76 | *

{@code
 77 |      *   Map map = singletonMap("foo", 1); // Or whatever
 78 |      *   List mapped = map.entrySet().stream()
 79 |      *                            .map(mappingEntry((key, value) -> key + value))
 80 |      *                            .collect(toList());
 81 |      * }
82 | * 83 | * @param mapper the mapping function for the values 84 | * @param key type, will not change 85 | * @param value type, will not change 86 | * @param target type 87 | * @return a mapper from entry to {@code OUT} 88 | */ 89 | public static Function, OUT> mappingEntry(BiFunction mapper) { 90 | return entry -> mapper.apply(entry.getKey(), entry.getValue()); 91 | } 92 | 93 | /** 94 | * A convenience function to consume map entries, e.g., when you need transformations during stream processing 95 | *

96 | * Example: 97 | *

{@code
 98 |      *   Map map = singletonMap("foo", 1); // Or whatever
 99 |      *   map.entrySet().stream()
100 |      *      .map(mappingValue((k, v) -> ...)
101 |      *      .forEach(consumingEntry((key, value) -> ...));
102 |      * }
103 | * 104 | * @param consumer the consumer function 105 | * @param key type 106 | * @param value type 107 | * @return a consumer for map entries 108 | */ 109 | public static Consumer> consumingEntry(BiConsumer consumer) { 110 | return entry -> consumer.accept(entry.getKey(), entry.getValue()); 111 | } 112 | 113 | /** 114 | * Convenience method to create a {@link java.util.AbstractMap.SimpleImmutableEntry} 115 | * @param key the key 116 | * @param value the value 117 | * @param key type 118 | * @param value type 119 | * @return entry with {@code key} as left side and {@code value} as right side 120 | */ 121 | public static Map.Entry entryOf(K key, V value) { 122 | return new AbstractMap.SimpleImmutableEntry<>(key, value); 123 | } 124 | } 125 | -------------------------------------------------------------------------------- /src/main/java/com/nitorcreations/streams/NStreams.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015- Nitor Creations Ltd. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | * 16 | */ 17 | 18 | package com.nitorcreations.streams; 19 | 20 | import java.util.Iterator; 21 | import java.util.Objects; 22 | import java.util.Optional; 23 | import java.util.stream.Stream; 24 | import java.util.stream.StreamSupport; 25 | 26 | public final class NStreams { 27 | private NStreams() { /** prevent instantiation */} 28 | 29 | /** 30 | * Convert an {@link Optional} to a {@link Stream} 31 | * @param optional the optional to convert to a stream 32 | * @param the type of the element 33 | * @return a stream containing the optional's value or empty stream if not present 34 | */ 35 | public static Stream asStream(Optional optional) { 36 | return optional.map(Stream::of).orElse(Stream.empty()); 37 | } 38 | 39 | /** 40 | * Convert an {@link Iterator} to a {@link Stream}. 41 | * 42 | * @param iterator the iterator to convert to a stream 43 | * @param the type of a single element 44 | * @return a stream containing the values of the iterator 45 | */ 46 | public static Stream asStream(Iterator iterator) { 47 | return asStream(iterator, false); 48 | } 49 | 50 | /** 51 | * Convert an {@link Iterator} to a {@link Stream}. 52 | * @param iterator the iterator to convert to a stream 53 | * @param the type of a single element 54 | * @param parallel if true then the returned stream is a parallel stream; if false the returned stream is a sequential stream. 55 | * @return a stream containing the values of the iterator 56 | */ 57 | public static Stream asStream(Iterator iterator, boolean parallel) { 58 | return asStream(() -> iterator, parallel); 59 | } 60 | 61 | /** 62 | * Convert an {@link Iterable} to a {@link Stream} 63 | * @param iterable the iterable to convert 64 | * @param the type of a single element 65 | * @return a (non-parallel) stream containing the values of the iterable 66 | */ 67 | public static Stream asStream(Iterable iterable) { 68 | return asStream(iterable, false); 69 | } 70 | 71 | /** 72 | * Convert an {@link Iterable} to a {@link Stream} 73 | * @param iterable the iterable to convert 74 | * @param parallel if true then the returned stream is a parallel stream; if false the returned stream is a sequential stream. 75 | * @param the type of a single element 76 | * @return a stream containing the values of the iterable 77 | */ 78 | public static Stream asStream(Iterable iterable, boolean parallel) { 79 | return Optional.ofNullable(iterable) 80 | .map(it -> StreamSupport.stream(it.spliterator(), parallel)) 81 | .orElse(Stream.empty()); 82 | } 83 | 84 | /** 85 | * Concatenate the given streams to a single stream. Follows the semantics 86 | * of {@link Stream#concat(Stream, Stream)}. 87 | * @param streams the streams to concatenate 88 | * @param type of the stream element 89 | * @return a stream containing all of the elements in all of the streams 90 | */ 91 | @SafeVarargs 92 | public static Stream concat(Stream ...streams) { 93 | return Stream.of(streams) 94 | .filter(Objects::nonNull) 95 | .reduce(Stream::concat).get(); 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /src/test/java/com/nitorcreations/collections/NMapsTest.java: -------------------------------------------------------------------------------- 1 | package com.nitorcreations.collections; 2 | 3 | import org.junit.Test; 4 | 5 | import java.lang.reflect.InvocationTargetException; 6 | import java.util.Map; 7 | 8 | import static com.nitorcreations.streams.NMappers.entryOf; 9 | import static com.nitorcreations.collections.NMaps.*; 10 | import static com.nitorcreations.collections.NSets.asSet; 11 | import static com.nitorcreations.test.TestUtils.invokePrivateConstructor; 12 | import static java.util.Arrays.asList; 13 | import static java.util.function.Function.identity; 14 | import static com.nitorcreations.test.Assertions.assertThat; 15 | 16 | public class NMapsTest { 17 | 18 | @Test 19 | public void forCoverage() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { 20 | invokePrivateConstructor(NMaps.class); 21 | } 22 | 23 | // 24 | // MAP OF ENTRIES 25 | // 26 | 27 | @Test 28 | public void testMapOfEntries() { 29 | final Map map = mapOfEntries(entryOf("a", "b"), entryOf("c", "d")); 30 | assertThat(map).hasSize(2) 31 | .containsEntry("a", "b") 32 | .containsEntry("c", "d"); 33 | } 34 | 35 | @Test 36 | public void testMapOfEntries_empty() { 37 | assertThat(mapOfEntries()).isEmpty(); 38 | } 39 | 40 | @Test(expected = NullPointerException.class) 41 | public void testMapOfEntries_nullEntry() { 42 | mapOfEntries(entryOf(1, 2), null); 43 | } 44 | 45 | // 46 | // MAPPING KEYS TO VALUES 47 | // 48 | @Test 49 | public void testMapping() { 50 | final Map map = mapping(asSet("a", "bee", "cheetah"), String::length); 51 | assertThat(map).hasSize(3) 52 | .containsEntry("a", 1) 53 | .containsEntry("bee", 3) 54 | .containsEntry("cheetah", 7); 55 | } 56 | 57 | @Test(expected = ArithmeticException.class) 58 | public void testMapping_withException() { 59 | mapping(asSet(1,2,0), i -> 10 / i); 60 | } 61 | 62 | @Test(expected = NullPointerException.class) 63 | public void testMapping_nullKeys() { 64 | mapping(asSet(1, null), identity()); 65 | } 66 | 67 | // 68 | // TEST COMBINE 69 | // 70 | @Test 71 | public void combineMaps() { 72 | final Map combined = combine(mapOf(1, 2), mapOf(3, 4)); 73 | assertThat(combined).hasSize(2) 74 | .containsEntry(1, 2) 75 | .containsEntry(3, 4); 76 | } 77 | 78 | @Test(expected = IllegalStateException.class) 79 | public void combineMapsDuplicateKeys() { 80 | combine(mapOf(1, 2), mapOf(1, 3)); 81 | } 82 | 83 | @Test 84 | public void combineMaps_summingOnDuplicate() { 85 | final Map combined = combine((a, b) -> a + b, mapOf(1, 2), mapOf(1, 3)); 86 | assertThat(combined).hasSize(1) 87 | .containsEntry(1, 5); // Summed 88 | } 89 | 90 | @Test 91 | public void combineMapsAndSkip_duplicateKeys_selectsFirst() { 92 | final Map map = combineAndSkip(mapOf(1, 2), mapOf(1, 3)); 93 | assertThat(map).hasSize(1).containsEntry(1, 2); 94 | } 95 | 96 | // 97 | // MAP OF LISTS 98 | // 99 | 100 | @Test 101 | public void testMapOfLists() { 102 | final Map map = mapOfLists(asList(1, 2, 3), asList("a", "b", "c")); 103 | assertThat(map).hasSize(3) 104 | .containsEntry(1, "a") 105 | .containsEntry(2, "b") 106 | .containsEntry(3, "c"); 107 | } 108 | 109 | @Test(expected = IllegalStateException.class) 110 | public void testMapOfLists_duplicateKeys() { 111 | mapOfLists(asList(1, 1, 1), asList(1, 2, 3)); 112 | } 113 | 114 | @Test(expected = IllegalArgumentException.class) 115 | public void testMapOfLists_differentSize() { 116 | mapOfLists(asList(1, 2, 3), asList(1, 2)); 117 | } 118 | 119 | @Test(expected = NullPointerException.class) 120 | public void testMapOfLists_nullKeys() { 121 | mapOfLists(null, asList(1, 2, 3)); 122 | } 123 | 124 | @Test(expected = NullPointerException.class) 125 | public void testMapOfLists_nullValues() { 126 | mapOfLists(asList(1, 2, 3), null); 127 | } 128 | 129 | // 130 | // HELPER MAP CREATION 131 | // 132 | 133 | @Test 134 | public void testMapOf_1() { 135 | assertThat(mapOf(1, 10)).hasSize(1).containsEntry(1, 10); 136 | } 137 | 138 | @Test 139 | public void testMapOf_2() { 140 | assertThat(mapOf(1, 10, 2, 20)) 141 | .hasSize(2) 142 | .containsEntry(1, 10) 143 | .containsEntry(2, 20); 144 | } 145 | 146 | @Test 147 | public void testMapOf_3() { 148 | assertThat(mapOf(1, 10, 2, 20, 3, 30)) 149 | .hasSize(3) 150 | .containsEntry(1, 10) 151 | .containsEntry(2, 20) 152 | .containsEntry(3, 30); 153 | } 154 | 155 | @Test 156 | public void testMapOf_4() { 157 | assertThat(mapOf(1, 10, 2, 20, 3, 30, 4, 40)) 158 | .hasSize(4) 159 | .containsEntry(1, 10) 160 | .containsEntry(2, 20) 161 | .containsEntry(3, 30) 162 | .containsEntry(4, 40); 163 | } 164 | 165 | @Test 166 | public void testMapOf_5() { 167 | assertThat(mapOf(1, 10, 2, 20, 3, 30, 4, 40, 5, 50)) 168 | .hasSize(5) 169 | .containsEntry(1, 10) 170 | .containsEntry(2, 20) 171 | .containsEntry(3, 30) 172 | .containsEntry(4, 40) 173 | .containsEntry(5, 50); 174 | } 175 | 176 | @Test 177 | public void testMapOf_6() { 178 | assertThat(mapOf(1, 10, 2, 20, 3, 30, 4, 40, 5, 50, 6, 60)) 179 | .hasSize(6) 180 | .containsEntry(1, 10) 181 | .containsEntry(2, 20) 182 | .containsEntry(3, 30) 183 | .containsEntry(4, 40) 184 | .containsEntry(5, 50) 185 | .containsEntry(6, 60); 186 | } 187 | 188 | @Test 189 | public void testMapOf_7() { 190 | assertThat(mapOf(1, 10, 2, 20, 3, 30, 4, 40, 5, 50, 6, 60, 7, 70)) 191 | .hasSize(7) 192 | .containsEntry(1, 10) 193 | .containsEntry(2, 20) 194 | .containsEntry(3, 30) 195 | .containsEntry(4, 40) 196 | .containsEntry(5, 50) 197 | .containsEntry(6, 60) 198 | .containsEntry(7, 70); 199 | } 200 | 201 | @Test 202 | public void testMapOf_8() { 203 | assertThat(mapOf(1, 10, 2, 20, 3, 30, 4, 40, 5, 50, 6, 60, 7, 70, 8, 80)) 204 | .hasSize(8) 205 | .containsEntry(1, 10) 206 | .containsEntry(2, 20) 207 | .containsEntry(3, 30) 208 | .containsEntry(4, 40) 209 | .containsEntry(5, 50) 210 | .containsEntry(6, 60) 211 | .containsEntry(7, 70) 212 | .containsEntry(8, 80); 213 | } 214 | 215 | @Test 216 | public void testMapOf_9() { 217 | assertThat(mapOf(1, 10, 2, 20, 3, 30, 4, 40, 5, 50, 6, 60, 7, 70, 8, 80, 9, 90)) 218 | .hasSize(9) 219 | .containsEntry(1, 10) 220 | .containsEntry(2, 20) 221 | .containsEntry(3, 30) 222 | .containsEntry(4, 40) 223 | .containsEntry(5, 50) 224 | .containsEntry(6, 60) 225 | .containsEntry(7, 70) 226 | .containsEntry(8, 80) 227 | .containsEntry(9, 90); 228 | } 229 | 230 | @Test 231 | public void testMapOf_10() { 232 | assertThat(mapOf(1, 10, 2, 20, 3, 30, 4, 40, 5, 50, 6, 60, 7, 70, 8, 80, 9, 90, 10, 100)) 233 | .hasSize(10) 234 | .containsEntry(1, 10) 235 | .containsEntry(2, 20) 236 | .containsEntry(3, 30) 237 | .containsEntry(4, 40) 238 | .containsEntry(5, 50) 239 | .containsEntry(6, 60) 240 | .containsEntry(7, 70) 241 | .containsEntry(8, 80) 242 | .containsEntry(9, 90) 243 | .containsEntry(10, 100); 244 | } 245 | 246 | @Test(expected = IllegalStateException.class) 247 | public void testMapOf_2_withDuplicates() { 248 | mapOf(1, 2, 1, 3); 249 | } 250 | } -------------------------------------------------------------------------------- /src/test/java/com/nitorcreations/collections/NSetsTest.java: -------------------------------------------------------------------------------- 1 | package com.nitorcreations.collections; 2 | 3 | import org.junit.Test; 4 | 5 | import java.lang.reflect.InvocationTargetException; 6 | import java.util.Set; 7 | 8 | import static com.nitorcreations.test.TestUtils.invokePrivateConstructor; 9 | import static com.nitorcreations.collections.NSets.asSet; 10 | import static java.util.Arrays.asList; 11 | import static com.nitorcreations.test.Assertions.assertThat; 12 | 13 | public class NSetsTest { 14 | 15 | @Test 16 | public void forCoverage() throws InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException { 17 | invokePrivateConstructor(NSets.class); 18 | } 19 | 20 | @Test 21 | public void testAsSet() { 22 | final Set strings = asSet("foo", "bar", "baz"); 23 | assertThat(strings).contains("foo", "bar", "baz"); 24 | } 25 | 26 | @Test 27 | public void testAsSet_nullValues() { 28 | final Set foo = asSet(null, null, null, "Foo"); 29 | assertThat(foo).hasSize(2).contains(null, "Foo"); 30 | } 31 | 32 | @Test 33 | public void testAsSet_iterable() { 34 | final Set strings = asSet(asList("foo", "bar", "baz")); 35 | assertThat(strings).contains("foo", "bar", "baz"); 36 | } 37 | 38 | @Test 39 | public void testAsSet_iterator() { 40 | final Set strings = asSet(asList("foo", "bar", "baz").iterator()); 41 | assertThat(strings).contains("foo", "bar", "baz"); 42 | } 43 | } -------------------------------------------------------------------------------- /src/test/java/com/nitorcreations/predicates/NCollectionPredicatesTest.java: -------------------------------------------------------------------------------- 1 | package com.nitorcreations.predicates; 2 | 3 | import org.junit.Test; 4 | 5 | import java.lang.reflect.InvocationTargetException; 6 | import java.util.ArrayList; 7 | import java.util.HashSet; 8 | 9 | import static com.nitorcreations.test.TestUtils.invokePrivateConstructor; 10 | import static com.nitorcreations.collections.NSets.asSet; 11 | import static com.nitorcreations.predicates.NCollectionPredicates.*; 12 | import static com.nitorcreations.test.Assertions.assertThat; 13 | import static java.util.Arrays.asList; 14 | import static java.util.Collections.emptyList; 15 | import static java.util.Collections.singletonList; 16 | 17 | public class NCollectionPredicatesTest { 18 | 19 | @Test 20 | public void forCoverage() throws InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException { 21 | invokePrivateConstructor(NCollectionPredicates.class); 22 | } 23 | 24 | @Test 25 | public void testEmpty() { 26 | assertThat(empty()) 27 | .matchesAll(new HashSet<>(), new ArrayList<>()) 28 | .matchesNone(null, singletonList(1), asSet(1)); 29 | } 30 | 31 | @Test 32 | public void testNotEmpty() { 33 | assertThat(notEmpty()) 34 | .matchesAll(singletonList(1), asSet(1)) 35 | .matchesNone(null, new HashSet<>(), new ArrayList<>()); 36 | } 37 | 38 | @Test 39 | public void testContains() { 40 | final Long num = 666_666L; 41 | assertThat(contains(num)) 42 | .matchesAll(asList(1L, num), asSet(num), singletonList(666_666L)) 43 | .matchesNone(null, emptyList(), singletonList(113L)); 44 | } 45 | 46 | @Test 47 | public void testContainsAll() { 48 | final Long n1 = 123_123L; 49 | final Long n2 = 321_321L; 50 | assertThat(containsAll(n1, n2)) 51 | .matchesAll(asList(n1, n2), asList(n2, n1), asSet(n1, n2)) 52 | .matchesNone(null, emptyList(), singletonList(113L)); 53 | } 54 | 55 | @Test 56 | public void testContainsAny() { 57 | final Long n1 = 123_123L; 58 | final Long n2 = 321_321L; 59 | assertThat(containsAny(n1, n2)) 60 | .matchesAll(singletonList(n1), singletonList(n2), asList(n1, n2), asList(n2, n1), asSet(n1, n2)) 61 | .matchesNone(null, emptyList(), singletonList(113L)); 62 | } 63 | 64 | @Test 65 | public void testDoesNotContain() { 66 | final Long num = 666_666L; 67 | assertThat(doesNotContain(num)) 68 | .matchesAll(emptyList(), singletonList(113L)) 69 | .matchesNone(null, asList(1L, num), asSet(num), singletonList(666_666L)); 70 | } 71 | 72 | @Test 73 | public void testDoesNotContainAnyOf() { 74 | assertThat(doesNotContainAnyOf(123L, 321L)) 75 | .matchesAll(emptyList(), singletonList(113L)) 76 | .matchesNone(null, asList(1L, 123L), asSet(321L), asList(2L, 3L, 123L, 321L)); 77 | } 78 | 79 | @Test 80 | public void testDoesNotContainAllOf() { 81 | assertThat(doesNotContainAllOf(123L, 321L)) 82 | .matchesAll(emptyList(), singletonList(123L), singletonList(321L)) 83 | .matchesNone(null, asList(2L, 3L, 123L, 321L)); 84 | } 85 | } -------------------------------------------------------------------------------- /src/test/java/com/nitorcreations/predicates/NComparablePredicatesTest.java: -------------------------------------------------------------------------------- 1 | package com.nitorcreations.predicates; 2 | 3 | import org.junit.Test; 4 | 5 | import java.lang.reflect.InvocationTargetException; 6 | 7 | import static com.nitorcreations.test.TestUtils.invokePrivateConstructor; 8 | import static com.nitorcreations.predicates.NComparablePredicates.*; 9 | import static com.nitorcreations.test.Assertions.assertThat; 10 | 11 | public class NComparablePredicatesTest { 12 | 13 | @Test 14 | public void forCoverage() throws InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException { 15 | invokePrivateConstructor(NComparablePredicates.class); 16 | } 17 | 18 | @Test 19 | public void testLessThan() { 20 | assertThat(lt(10)) 21 | .matchesAll(Integer.MIN_VALUE, -1, 0, 1, 9) 22 | .matchesNone(10, 11, Integer.MAX_VALUE); 23 | } 24 | 25 | @Test 26 | public void testLessThanOrEqual() { 27 | assertThat(lte(10)) 28 | .matchesAll(Integer.MIN_VALUE, -1, 0, 1, 9, 10) 29 | .matchesNone(11, Integer.MAX_VALUE); 30 | } 31 | 32 | @Test 33 | public void testGreaterThan() { 34 | assertThat(gt(10)) 35 | .matchesNone(Integer.MIN_VALUE, -1, 0, 1, 9, 10) 36 | .matchesAll(11, Integer.MAX_VALUE); 37 | } 38 | 39 | @Test 40 | public void testGreaterThanOrEqual() { 41 | assertThat(gte(10)) 42 | .matchesNone(Integer.MIN_VALUE, -1, 0, 1, 9) 43 | .matchesAll(10, 11, Integer.MAX_VALUE); 44 | } 45 | } -------------------------------------------------------------------------------- /src/test/java/com/nitorcreations/predicates/NOptionalPredicatesTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015- Nitor Creations Ltd. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | * 16 | */ 17 | 18 | package com.nitorcreations.predicates; 19 | 20 | import org.junit.Test; 21 | 22 | import java.lang.reflect.InvocationTargetException; 23 | import java.util.List; 24 | import java.util.Optional; 25 | import java.util.stream.Stream; 26 | 27 | import static com.nitorcreations.predicates.NOptionalPredicates.*; 28 | import static com.nitorcreations.predicates.NPredicates.having; 29 | import static com.nitorcreations.test.TestUtils.invokePrivateConstructor; 30 | import static java.util.stream.Collectors.toList; 31 | import static com.nitorcreations.test.Assertions.assertThat; 32 | 33 | public class NOptionalPredicatesTest { 34 | 35 | private final Optional emptyOpt = Optional.empty(); 36 | private final Optional opt = Optional.of("Foo"); 37 | 38 | @Test 39 | public void forCoverage() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { 40 | invokePrivateConstructor(NOptionalPredicates.class); 41 | } 42 | 43 | @Test 44 | public void testEmpty() { 45 | assertThat(empty()).matches(emptyOpt).doesNotMatch(opt); 46 | } 47 | 48 | @Test 49 | public void testPresent() { 50 | assertThat(present()).matches(opt).doesNotMatch(emptyOpt); 51 | } 52 | 53 | @Test 54 | public void testHavingValue() { 55 | assertThat(havingValue("Foo")).matches(opt); 56 | assertThat(havingValue("Bar")).doesNotMatch(opt); 57 | 58 | assertThat(havingValue((String) null)).doesNotMatch(opt); 59 | } 60 | 61 | @Test 62 | public void testNotHavingValue() { 63 | assertThat(notHavingValue("Foo")).doesNotMatch(opt); 64 | assertThat(notHavingValue("Bar")).matches(opt); 65 | 66 | assertThat(notHavingValue((String) null)).matches(opt); 67 | } 68 | 69 | @Test 70 | public void testThatWorksAsFilter() { 71 | final List strings = Stream.of(emptyOpt, emptyOpt, emptyOpt, opt, opt, emptyOpt, opt) 72 | .filter(present()) 73 | .map(Optional::get) 74 | .collect(toList()); 75 | assertThat(strings).containsExactly("Foo", "Foo", "Foo"); 76 | } 77 | 78 | @Test 79 | public void testChainingPredicates() { 80 | final List strings = Stream.of( 81 | emptyOpt, 82 | Optional.of("1"), 83 | Optional.of("12"), 84 | Optional.of("123"), 85 | emptyOpt, 86 | Optional.of("1234"), 87 | Optional.of("12345"), 88 | Optional.of("123456"), 89 | emptyOpt 90 | ).filter(havingValue(having(Integer::parseInt, i -> i > 100))) 91 | .map(Optional::get) 92 | .collect(toList()); 93 | 94 | assertThat(strings) 95 | .contains("123", "1234", "12345", "123456"); 96 | } 97 | } -------------------------------------------------------------------------------- /src/test/java/com/nitorcreations/predicates/NPredicatesTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015- Nitor Creations Ltd. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | * 16 | */ 17 | 18 | package com.nitorcreations.predicates; 19 | 20 | import org.assertj.core.util.Strings; 21 | import org.junit.Test; 22 | 23 | import java.lang.reflect.InvocationTargetException; 24 | 25 | import static com.nitorcreations.predicates.NPredicates.*; 26 | import static com.nitorcreations.test.Assertions.assertThat; 27 | import static com.nitorcreations.test.TestUtils.invokePrivateConstructor; 28 | 29 | public class NPredicatesTest { 30 | final Object o2 = new Object(); 31 | final Object o1 = new Object(); 32 | final Object nullObject = null; 33 | 34 | final String s1 = "Foobar"; 35 | final String s2 = "Baz"; 36 | final String nullString = null; 37 | 38 | @Test 39 | public void forCoverage() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { 40 | invokePrivateConstructor(NPredicates.class); 41 | } 42 | 43 | @Test 44 | public void testIs() { 45 | assertThat(is(o1).test(o1)).isTrue(); 46 | assertThat(is(o2).test(o2)).isTrue(); 47 | assertThat(is(o1).test(o2)).isFalse(); 48 | assertThat(is(o2).test(o1)).isFalse(); 49 | assertThat(is(null).test(null)).isTrue(); 50 | } 51 | 52 | @Test 53 | public void testNot() { 54 | assertThat(not(o1).test(o1)).isFalse(); 55 | assertThat(not(o2).test(o2)).isFalse(); 56 | assertThat(not(o1).test(o2)).isTrue(); 57 | assertThat(not(o2).test(o1)).isTrue(); 58 | assertThat(not((Object)null).test(null)).isFalse(); 59 | } 60 | 61 | @Test 62 | public void testEqualTo() { 63 | assertThat(equalTo(s1).test(s1)).isTrue(); 64 | assertThat(equalTo(s2).test(s2)).isTrue(); 65 | assertThat(equalTo(s1).test("Foobar")).isTrue(); 66 | assertThat(equalTo("Baz").test(s2)).isTrue(); 67 | assertThat(equalTo(s1).test(s2)).isFalse(); 68 | assertThat(equalTo(s2).test(s1)).isFalse(); 69 | assertThat(equalTo(null).test(null)).isTrue(); 70 | } 71 | 72 | @Test 73 | public void testNotEqualTo() { 74 | assertThat(notEqualTo(s1).test(s1)).isFalse(); 75 | assertThat(notEqualTo(s2).test(s2)).isFalse(); 76 | assertThat(notEqualTo(s1).test("Foobar")).isFalse(); 77 | assertThat(notEqualTo("Baz").test(s2)).isFalse(); 78 | assertThat(notEqualTo(s1).test(s2)).isTrue(); 79 | assertThat(notEqualTo(s2).test(s1)).isTrue(); 80 | assertThat(notEqualTo(null).test(null)).isFalse(); 81 | } 82 | 83 | @Test 84 | public void testIsNull() { 85 | assertThat(isNull().test(nullString)).isTrue(); 86 | assertThat(isNull().test(s1)).isFalse(); 87 | } 88 | 89 | @Test 90 | public void testNotNull() { 91 | assertThat(notNull().test(s1)).isTrue(); 92 | assertThat(notNull().test(nullString)).isFalse(); 93 | } 94 | 95 | @Test 96 | public void testHaving() { 97 | assertThat(having(String::length, is(3)).test(s1)).isFalse(); 98 | assertThat(having(String::length, is(3)).test(s2)).isTrue(); 99 | } 100 | 101 | @Test 102 | public void testHavingEqual() { 103 | assertThat(havingEqual(String::length, 3).test(s1)).isFalse(); 104 | assertThat(havingEqual(String::length, 3).test(s2)).isTrue(); 105 | } 106 | 107 | @Test 108 | public void testHavingShorthand() { 109 | assertThat(having(Strings::isNullOrEmpty).test(s1)).isFalse(); 110 | assertThat(having(Strings::isNullOrEmpty).test(nullString)).isTrue(); 111 | } 112 | 113 | @Test 114 | public void testNotHavingShorthand() { 115 | assertThat(notHaving(Strings::isNullOrEmpty).test(s1)).isTrue(); 116 | assertThat(notHaving(Strings::isNullOrEmpty).test(nullString)).isFalse(); 117 | } 118 | 119 | @Test 120 | public void testAllOf() { 121 | assertThat(allOf(notNull(), is(123l))) 122 | .matches(123l) 123 | .matchesNone(null, 122l); 124 | } 125 | 126 | @Test 127 | public void testAnyOf() { 128 | assertThat(anyOf(is(123l), isNull())) 129 | .matchesAll(null, 123l) 130 | .matchesNone(122l); 131 | } 132 | 133 | @Test(expected = IllegalArgumentException.class) 134 | public void testAllOf_emptyArgs() { 135 | allOf(); 136 | } 137 | 138 | @Test(expected = IllegalArgumentException.class) 139 | public void testAnyOf_emptyArgs() { 140 | anyOf(); 141 | } 142 | } -------------------------------------------------------------------------------- /src/test/java/com/nitorcreations/predicates/NStringPredicatesTest.java: -------------------------------------------------------------------------------- 1 | package com.nitorcreations.predicates; 2 | 3 | import org.junit.Test; 4 | 5 | import java.lang.reflect.InvocationTargetException; 6 | 7 | import static com.nitorcreations.test.TestUtils.invokePrivateConstructor; 8 | import static com.nitorcreations.predicates.NStringPredicates.*; 9 | import static com.nitorcreations.test.Assertions.assertThat; 10 | 11 | public class NStringPredicatesTest { 12 | 13 | @Test 14 | public void forCoverage() throws InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException { 15 | invokePrivateConstructor(NStringPredicates.class); 16 | } 17 | 18 | @Test 19 | public void testStartsWith() { 20 | assertThat(startsWith("foo")) 21 | .matchesAll("foo", "foobar", "foooo") 22 | .matchesNone("bar", "fo", "", null); 23 | } 24 | 25 | @Test 26 | public void testEndsWith() { 27 | assertThat(endsWith("bar")) 28 | .matchesAll("bar", "foobar", "foooobarbar") 29 | .matchesNone("barr", "byar", "", null); 30 | } 31 | 32 | @Test 33 | public void testIsBlank() { 34 | assertThat(isBlank()) 35 | .matchesAll("", " ", "\n \n", null) 36 | .matchesNone("a", "\n\na"); 37 | } 38 | 39 | @Test 40 | public void testNotBlank() { 41 | assertThat(notBlank()) 42 | .matchesAll("a", "\n\na") 43 | .matchesNone(null, "", " ", "\n \n"); 44 | } 45 | 46 | @Test 47 | public void testContains() { 48 | assertThat(contains("foo")) 49 | .matchesAll("foo", "foobar", "barquxfoo", "osdfooasd") 50 | .matchesNone("bar", "", null, "fo o"); 51 | } 52 | 53 | @Test 54 | public void testContainsAll() { 55 | assertThat(containsAll("foo", "oof")) 56 | .matchesAll("foof", "foobaroof", "foooooooof", "foo roof") 57 | .matchesNone("foo", "oof", "", null, "fo of"); 58 | } 59 | 60 | @Test 61 | public void testContainsAll_emptyContains() { 62 | assertThat(containsAll()) 63 | .matchesAll("", "sadfdsf", "osvfibjisf osbjoiab oj") 64 | .matchesNone((String) null); 65 | } 66 | 67 | @Test 68 | public void testContainsAny() { 69 | assertThat(containsAny("foo", "oof")) 70 | .matchesAll("foo", "oof", "foof", "foobaroof", "foooooooof", "foo roof") 71 | .matchesNone("", null, "fo of"); 72 | } 73 | 74 | @Test 75 | public void testDoesNotContain() { 76 | assertThat(doesNotContain("foo")) 77 | .matchesAll("", "bar", "baz", "of", "fo", "fo of") 78 | .matchesNone(null, "foo", "foobar", "ooffoo", "barfoo", "barfooazx"); 79 | } 80 | 81 | @Test 82 | public void testDoesNotContainAnyOf() { 83 | assertThat(doesNotContainAnyOf("foo", "bar")) 84 | .matchesAll("", "baz", "of", "fo", "fo of") 85 | .matchesNone(null, "foo", "bar", "foobar", "ooffoo", "barfoo", "barfooazx"); 86 | } 87 | 88 | @Test 89 | public void testDoesNotContainAllOf() { 90 | assertThat(doesNotContainAllOf("foo", "bar")) 91 | .matchesAll("", "baz", "of", "fo", "fo of", "foo ba", "fo bar", "foo", "bar") 92 | .matchesNone(null, "foobar", "barfoo", "barfooazx"); 93 | } 94 | 95 | } -------------------------------------------------------------------------------- /src/test/java/com/nitorcreations/streams/Fixture.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015- Nitor Creations Ltd. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | * 16 | */ 17 | 18 | package com.nitorcreations.streams; 19 | 20 | import java.util.AbstractMap; 21 | import java.util.LinkedHashMap; 22 | import java.util.List; 23 | import java.util.Map; 24 | 25 | import static java.util.Arrays.asList; 26 | 27 | public class Fixture { 28 | private Fixture() { /** prevent instantiation */} 29 | 30 | public static Map linkedMap; 31 | 32 | public static List listWithDuplicates = asList("Foo", "Bar", "Baz", "Qux", "Foo", "Foo", "Foo", "Baz"); 33 | 34 | static { 35 | linkedMap = new LinkedHashMap<>(); 36 | linkedMap.put("Eka", 1); 37 | linkedMap.put("Toka", 2); 38 | linkedMap.put("Kolmas", 3); 39 | linkedMap.put("Neljäs", 4); 40 | linkedMap.put("Viides", 5); 41 | linkedMap.put("Kuudes", 6); 42 | } 43 | 44 | public static List> entries = asList( 45 | entry("Eka", 3), 46 | entry("Toka", 4), 47 | entry("Kolmas", 5) 48 | ); 49 | 50 | public static List> entriesWithDuplicates = asList( 51 | entry("Eka", 1), 52 | entry("Eka", 2), 53 | entry("Eka", 3), 54 | entry("Toka", 4), 55 | entry("Kolmas", 5) 56 | ); 57 | 58 | public static Map.Entry entry(K key, V value) { 59 | return new AbstractMap.SimpleImmutableEntry<>(key, value); 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/test/java/com/nitorcreations/streams/NCollectorsTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015- Nitor Creations Ltd. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | * 16 | */ 17 | 18 | package com.nitorcreations.streams; 19 | 20 | import org.junit.Test; 21 | 22 | import java.lang.reflect.InvocationTargetException; 23 | import java.util.List; 24 | import java.util.Map; 25 | 26 | import static com.nitorcreations.streams.Fixture.entriesWithDuplicates; 27 | import static com.nitorcreations.streams.Fixture.entries; 28 | import static com.nitorcreations.streams.Fixture.listWithDuplicates; 29 | import static com.nitorcreations.streams.NCollectors.countingOccurrences; 30 | import static com.nitorcreations.streams.NCollectors.entriesToMap; 31 | import static com.nitorcreations.test.TestUtils.invokePrivateConstructor; 32 | import static com.nitorcreations.test.Assertions.assertThat; 33 | import static org.assertj.core.util.Lists.emptyList; 34 | 35 | public class NCollectorsTest { 36 | 37 | @Test 38 | public void forCoverage() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { 39 | invokePrivateConstructor(NCollectors.class); 40 | } 41 | 42 | // 43 | // COUNT OCCURRENCES 44 | // 45 | 46 | @Test 47 | public void countingOccurrencesWorks() { 48 | final Map occurrences = listWithDuplicates.stream().collect(countingOccurrences()); 49 | assertThat(occurrences) 50 | .hasSize(4) 51 | .containsEntry("Foo", 4L) 52 | .containsEntry("Bar", 1L) 53 | .containsEntry("Baz", 2L) 54 | .containsEntry("Qux", 1L); 55 | } 56 | 57 | @Test 58 | public void countingOccurencesEmptyList() { 59 | final List strings = emptyList(); 60 | final Map occurrences = strings.stream().collect(countingOccurrences()); 61 | assertThat(occurrences).isEmpty(); 62 | } 63 | 64 | // 65 | // COLLECT ENTRIES TO MAP 66 | // 67 | 68 | @Test(expected = IllegalStateException.class) 69 | public void collectingEntriesWithDuplicatesToMap() { 70 | entriesWithDuplicates.stream().collect(entriesToMap()); 71 | } 72 | 73 | @Test 74 | public void collectingEntriesWithDuplicatesWithMapping() { 75 | final Map map = entriesWithDuplicates.stream().collect(entriesToMap((a, b) -> a + b)); 76 | assertThat(map) 77 | .hasSize(3) 78 | .containsEntry("Eka", 6) // Summed 79 | .containsEntry("Toka", 4) 80 | .containsEntry("Kolmas", 5); 81 | } 82 | 83 | @Test 84 | public void collectingEntriesWithoutDuplicates() { 85 | final Map map = entries.stream().distinct().collect(entriesToMap()); 86 | assertThat(map) 87 | .hasSize(3) 88 | .containsEntry("Eka", 3) 89 | .containsEntry("Toka", 4) 90 | .containsEntry("Kolmas", 5); 91 | } 92 | } -------------------------------------------------------------------------------- /src/test/java/com/nitorcreations/streams/NExtractorsTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015- Nitor Creations Ltd. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | * 16 | */ 17 | 18 | package com.nitorcreations.streams; 19 | 20 | import org.junit.Test; 21 | 22 | import java.lang.reflect.InvocationTargetException; 23 | 24 | import static com.nitorcreations.streams.Fixture.linkedMap; 25 | import static com.nitorcreations.streams.NExtractors.*; 26 | import static com.nitorcreations.test.TestUtils.invokePrivateConstructor; 27 | import static java.util.Collections.emptyMap; 28 | import static java.util.function.Function.identity; 29 | import static com.nitorcreations.test.Assertions.assertThat; 30 | 31 | public class NExtractorsTest { 32 | 33 | @Test 34 | public void forCoverage() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { 35 | invokePrivateConstructor(NExtractors.class); 36 | } 37 | // 38 | // DO WITH KEYS 39 | // 40 | 41 | @Test 42 | public void extractKeysToSetWorks() { 43 | assertThat(extractKeysToSet(linkedMap, String::length)).contains(3,4,6); 44 | assertThat(extractKeysToSet(emptyMap(), String::length)).isEmpty(); 45 | } 46 | 47 | @Test(expected = NullPointerException.class) 48 | public void extractKeysToSet_null() { 49 | extractKeysToSet(null, String::length); 50 | } 51 | 52 | @Test 53 | public void extractKeysToListWorks_keepsOrder() { 54 | assertThat(extractKeysToList(linkedMap, String::length)) 55 | .containsExactly(3,4,6,6,6,6); 56 | assertThat(extractKeysToList(emptyMap(), String::length)) 57 | .isEmpty(); 58 | } 59 | 60 | @Test(expected = NullPointerException.class) 61 | public void extractKeysToList_null() { 62 | extractKeysToList(null, String::length); 63 | } 64 | 65 | // 66 | // DO WITH VALUES 67 | // 68 | 69 | @Test 70 | public void extractValuesToSetWorks() { 71 | assertThat(extractValuesToSet(linkedMap, identity())).contains(1,2,3,4,5,6); 72 | assertThat(extractValuesToSet(emptyMap(), String::length)).isEmpty(); 73 | } 74 | 75 | @Test(expected = NullPointerException.class) 76 | public void extractValuesToSet_null() { 77 | extractValuesToSet(null, String::length); 78 | } 79 | 80 | @Test 81 | public void extractValuesToListWorks_keepsOrder() { 82 | assertThat(extractValuesToList(linkedMap, identity())) 83 | .containsExactly(1,2,3,4,5,6); 84 | assertThat(extractValuesToList(emptyMap(), String::length)) 85 | .isEmpty(); 86 | } 87 | 88 | @Test(expected = NullPointerException.class) 89 | public void extractValuesToList_null() { 90 | extractValuesToList(null, String::length); 91 | } 92 | 93 | } -------------------------------------------------------------------------------- /src/test/java/com/nitorcreations/streams/NMappersTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015- Nitor Creations Ltd. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | * 16 | */ 17 | 18 | package com.nitorcreations.streams; 19 | 20 | import org.junit.Test; 21 | 22 | import java.lang.reflect.InvocationTargetException; 23 | import java.util.ArrayList; 24 | import java.util.List; 25 | import java.util.Map; 26 | 27 | import static com.nitorcreations.streams.Fixture.linkedMap; 28 | import static com.nitorcreations.streams.NCollectors.entriesToMap; 29 | import static com.nitorcreations.streams.NMappers.*; 30 | import static com.nitorcreations.test.TestUtils.invokePrivateConstructor; 31 | import static java.util.stream.Collectors.toList; 32 | import static com.nitorcreations.test.Assertions.assertThat; 33 | 34 | public class NMappersTest { 35 | 36 | @Test 37 | public void forCoverage() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { 38 | invokePrivateConstructor(NMappers.class); 39 | } 40 | 41 | @Test 42 | public void test_mappingValue() { 43 | final Map mapped = linkedMap.entrySet().stream() 44 | .map(mappingValue((key, val) -> key + val)) 45 | .collect(entriesToMap()); 46 | 47 | assertThat(mapped) 48 | .containsKeys("Eka", "Toka", "Kolmas", "Neljäs", "Viides", "Kuudes") 49 | .containsValues("Eka1", "Toka2", "Kolmas3", "Neljäs4", "Viides5", "Kuudes6"); 50 | } 51 | 52 | @Test 53 | public void test_mappingKey() { 54 | final Map mapped = linkedMap.entrySet().stream() 55 | .map(mappingKey((key, val) -> key + val)) 56 | .collect(entriesToMap()); 57 | 58 | assertThat(mapped) 59 | .containsKeys("Eka1", "Toka2", "Kolmas3", "Neljäs4", "Viides5", "Kuudes6") 60 | .containsValues(1,2,3,4,5,6); 61 | } 62 | 63 | @Test 64 | public void test_mappingEntry() { 65 | final List combined = linkedMap.entrySet().stream() 66 | .map(mappingEntry((k, v) -> k + v)) 67 | .collect(toList()); 68 | 69 | assertThat(combined).containsExactly("Eka1", "Toka2", "Kolmas3", "Neljäs4", "Viides5", "Kuudes6"); 70 | } 71 | 72 | @Test 73 | public void test_consumingEntry() { 74 | final List combined = new ArrayList<>(); 75 | linkedMap.entrySet().forEach(consumingEntry((k,v) -> { 76 | combined.add(k+v); 77 | })); 78 | assertThat(combined).containsExactly("Eka1", "Toka2", "Kolmas3", "Neljäs4", "Viides5", "Kuudes6"); 79 | } 80 | } -------------------------------------------------------------------------------- /src/test/java/com/nitorcreations/streams/NStreamsTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015- Nitor Creations Ltd. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | * 16 | */ 17 | 18 | package com.nitorcreations.streams; 19 | 20 | import org.junit.Test; 21 | 22 | import java.lang.reflect.InvocationTargetException; 23 | import java.util.ArrayList; 24 | import java.util.List; 25 | import java.util.NoSuchElementException; 26 | import java.util.Optional; 27 | import java.util.stream.Collectors; 28 | import java.util.stream.Stream; 29 | 30 | import static com.nitorcreations.streams.NStreams.asStream; 31 | import static com.nitorcreations.test.TestUtils.invokePrivateConstructor; 32 | import static java.util.Arrays.asList; 33 | import static java.util.stream.Collectors.toList; 34 | import static com.nitorcreations.test.Assertions.assertThat; 35 | 36 | public class NStreamsTest { 37 | 38 | private Optional opt = Optional.of("Foo"); 39 | private Optional emptyOpt = Optional.empty(); 40 | 41 | final List list = asList(1, 2, 3, 4, 5); 42 | 43 | @Test 44 | public void forCoverage() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { 45 | invokePrivateConstructor(NStreams.class); 46 | } 47 | 48 | @Test 49 | public void testOptionalToStream() { 50 | final List strings = asStream(opt).collect(toList()); 51 | assertThat(strings).containsExactly("Foo"); 52 | } 53 | 54 | @Test 55 | public void testEmptyOptionalToStream() { 56 | final List strings = asStream(emptyOpt).collect(toList()); 57 | assertThat(strings).isEmpty(); 58 | } 59 | 60 | @Test 61 | public void iteratorToStream() { 62 | final List actual = asStream(list.listIterator()).collect(toList()); 63 | assertThat(actual).containsExactlyElementsOf(list); 64 | } 65 | 66 | @Test 67 | public void nullToEmptyStream() { 68 | final Stream actual = asStream((Iterable) null); 69 | assertThat(actual.collect(Collectors.toList())).isEmpty(); 70 | } 71 | 72 | @Test 73 | public void iteratorToStream_parallel() { 74 | final List actual = asStream(list.iterator(), true).collect(toList()); 75 | assertThat(actual) 76 | .containsOnlyElementsOf(list) 77 | .containsAll(list); 78 | } 79 | 80 | @Test 81 | public void iterableToStream() { 82 | final List actual = asStream(list).collect(toList()); 83 | assertThat(actual).containsExactlyElementsOf(list); 84 | } 85 | 86 | @Test 87 | public void iterableToStream_parallel() { 88 | final List actual = asStream(list, true).collect(toList()); 89 | assertThat(actual) 90 | .containsOnlyElementsOf(list) 91 | .containsAll(list); 92 | } 93 | 94 | @Test 95 | public void test_concatenation_empty_lists() { 96 | List emptylist = new ArrayList<>(); 97 | List combinedList = NStreams.concat(emptylist.stream(), emptylist.stream()) 98 | .collect(toList()); 99 | assertThat(combinedList).isEmpty(); 100 | } 101 | 102 | @Test 103 | public void test_concatenation() { 104 | List list1 = asList("1", "11"); 105 | List list2 = asList("2", "22"); 106 | List list3 = asList("3"); 107 | 108 | List combinedList = NStreams.concat(list1.stream(), list2.stream(), list3.stream()).collect(toList()); 109 | assertThat(combinedList).containsExactly("1","11","2","22","3"); 110 | } 111 | 112 | @Test(expected = NoSuchElementException.class) 113 | public void test_concatNulls() { 114 | NStreams.concat(); 115 | } 116 | 117 | } -------------------------------------------------------------------------------- /src/test/java/com/nitorcreations/test/Assertions.java: -------------------------------------------------------------------------------- 1 | package com.nitorcreations.test; 2 | 3 | import java.util.function.Predicate; 4 | 5 | public class Assertions extends org.assertj.core.api.Assertions { 6 | 7 | public static PredicateAssert assertThat(Predicate predicate) { 8 | return PredicateAssert.assertThat(predicate); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /src/test/java/com/nitorcreations/test/PredicateAssert.java: -------------------------------------------------------------------------------- 1 | package com.nitorcreations.test; 2 | 3 | import org.assertj.core.api.AbstractAssert; 4 | 5 | import java.util.Arrays; 6 | import java.util.List; 7 | import java.util.function.Predicate; 8 | 9 | import static com.nitorcreations.predicates.NPredicates.not; 10 | import static java.util.stream.Collectors.toList; 11 | 12 | public class PredicateAssert extends AbstractAssert, Predicate> { 13 | 14 | PredicateAssert(Predicate actual) { 15 | super(actual, PredicateAssert.class); 16 | } 17 | 18 | static PredicateAssert assertThat(Predicate predicate) { 19 | return new PredicateAssert<>(predicate); 20 | } 21 | 22 | public PredicateAssert matches(T testable) { 23 | isNotNull(); 24 | if (!actual.test(testable)) { 25 | failWithMessage("Expected predicate to match <%s>, but failed", testable); 26 | } 27 | return this; 28 | } 29 | 30 | public PredicateAssert doesNotMatch(T testable) { 31 | isNotNull(); 32 | if (actual.test(testable)) { 33 | failWithMessage("Expected predicate not to match <%s>, but matched", testable); 34 | } 35 | return this; 36 | } 37 | 38 | @SafeVarargs 39 | public final PredicateAssert matchesAll(T... testables) { 40 | isNotNull(); 41 | final List errors = Arrays.stream(testables) 42 | .filter(not(actual)) 43 | .collect(toList()); 44 | if (errors.size() > 0) { 45 | failWithMessage("Expected predicate to match all of <%s>, but did not match <%s>", Arrays.asList(testables), errors); 46 | } 47 | return this; 48 | } 49 | 50 | @SafeVarargs 51 | public final PredicateAssert matchesNone(T... testables) { 52 | isNotNull(); 53 | final List errors = Arrays.stream(testables) 54 | .filter(actual) 55 | .collect(toList()); 56 | if (errors.size() > 0) { 57 | failWithMessage("Expected predicate not to match any of <%s>, but matched <%s>", Arrays.asList(testables), errors); 58 | } 59 | return this; 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/test/java/com/nitorcreations/test/TestUtils.java: -------------------------------------------------------------------------------- 1 | package com.nitorcreations.test; 2 | 3 | import java.lang.reflect.Constructor; 4 | import java.lang.reflect.InvocationTargetException; 5 | 6 | public class TestUtils { 7 | public static void invokePrivateConstructor(Class clazz) throws NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException { 8 | final Constructor constructor = clazz.getDeclaredConstructor(); 9 | constructor.setAccessible(true); 10 | constructor.newInstance(); 11 | } 12 | } 13 | --------------------------------------------------------------------------------