From 32c833822e51d362b08f6f5c8fa6ca42abd53bd6 Mon Sep 17 00:00:00 2001 From: Ruslan Sibgatullin Date: Thu, 12 Jul 2018 23:13:31 +0300 Subject: [PATCH] LANG-1404 BooleanUtils.toBoolean(Integer) method added --- .../apache/commons/lang3/BooleanUtils.java | 20 +++++++++++++++++++ .../commons/lang3/BooleanUtilsTest.java | 13 ++++++++++++ 2 files changed, 33 insertions(+) diff --git a/src/main/java/org/apache/commons/lang3/BooleanUtils.java b/src/main/java/org/apache/commons/lang3/BooleanUtils.java index fdeff74a0d9..388091081d3 100644 --- a/src/main/java/org/apache/commons/lang3/BooleanUtils.java +++ b/src/main/java/org/apache/commons/lang3/BooleanUtils.java @@ -198,6 +198,26 @@ public static boolean toBoolean(final int value) { return value != 0; } + /** + *

Converts an Integer to a boolean using the convention that {@code zero} + * and {@code null} is {@code false}.

+ * + *
+     *   BooleanUtils.toBoolean(null) = false
+     *   BooleanUtils.toBoolean(Integer.valueOf(0)) = false
+     *   BooleanUtils.toBoolean(Integer.valueOf(1)) = true
+     *   BooleanUtils.toBoolean(Integer.valueOf(2)) = true
+     * 
+ * + * @param value the int to convert + * @return {@code true} if non-zero and non-null, + * {@code false} otherwise + * @since 3.8 + */ + public static boolean toBoolean(final Integer value) { + return value != null && value != 0; + } + /** *

Converts an int to a Boolean using the convention that {@code zero} * is {@code false}.

diff --git a/src/test/java/org/apache/commons/lang3/BooleanUtilsTest.java b/src/test/java/org/apache/commons/lang3/BooleanUtilsTest.java index 4fd3ad84154..0a70313698f 100644 --- a/src/test/java/org/apache/commons/lang3/BooleanUtilsTest.java +++ b/src/test/java/org/apache/commons/lang3/BooleanUtilsTest.java @@ -109,6 +109,19 @@ public void test_toBoolean_int() { assertFalse(BooleanUtils.toBoolean(0)); } + @Test + public void test_toBoolean_Integer() { + final Integer one = Integer.valueOf(1); + final Integer minusOne = Integer.valueOf(-1); + final Integer zero = Integer.valueOf(0); + final Integer nullInteger = null; + + assertEquals(Boolean.TRUE, BooleanUtils.toBoolean(one)); + assertEquals(Boolean.TRUE, BooleanUtils.toBoolean(minusOne)); + assertEquals(Boolean.FALSE, BooleanUtils.toBoolean(zero)); + assertEquals(Boolean.FALSE, BooleanUtils.toBoolean(nullInteger)); + } + @Test public void test_toBooleanObject_int() { assertEquals(Boolean.TRUE, BooleanUtils.toBooleanObject(1));