Skip to content

How to Find the Smallest Integer in the Array in Java

The challenge

Given an array of integers your solution should find the smallest integer.

For example:

  • Given [34, 15, 88, 2] your solution will return 2
  • Given [34, -345, -1, 100] your solution will return -345

You can assume, for the purpose of this challenge, that the supplied array will not be empty.

The solution in Java

Option 1 (using Arrays.sort):

import java.util.Arrays; public class SmallestIntegerFinder { public static int findSmallestInt(int[] args) { Arrays.sort(args); return args[]; } }
Code language: Java (java)

Option 2 (using streams):

import java.util.stream.IntStream; public class SmallestIntegerFinder { public static int findSmallestInt(int[] args) { return IntStream.of(args).min().getAsInt(); } }
Code language: Java (java)

Test cases to validate the solution

import org.junit.Test; import static org.junit.Assert.assertEquals; public class SmallestIntegerFinderTest { @Test public void example1(){ int expected = 11; int actual = SmallestIntegerFinder.findSmallestInt(new int[]{78,56,232,12,11,43}); assertEquals(expected, actual); } @Test public void example2(){ int expected = -33; int actual = SmallestIntegerFinder.findSmallestInt(new int[]{78,56,-2,12,8,-33}); assertEquals(expected, actual); } @Test public void example3(){ int expected = Integer.MIN_VALUE; int actual = SmallestIntegerFinder.findSmallestInt(new int[]{,Integer.MIN_VALUE,Integer.MAX_VALUE}); assertEquals(expected, actual); } }
Code language: Java (java)

See also  Find Numbers which are Divisible by given Number in Java
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x