Question

How can I achieve the following array print using Java 8's lambda expressions?

int[] values = new int[16];
// Populate values

for (int value : values) {
    System.out.println(Integer.toUnsignedString(value, 16));
}
Was it helpful?

Solution

Arrays.stream(values)
      .mapToObj(i -> Integer.toUnsignedString(i, 16))
      .forEach(System.out::println);

OTHER TIPS

String[] nums = {"three","two","one"};
Arrays.stream(nums).forEach(num -> System.out.println(num));

You can print the array in a simple way just by using one line of code instead of writing a loop, using Java8 features i.e. stream and method references

Example:

int arrayName[] = new int[size];

Arrays.stream(arrayName).forEach(System.out::println); //This will iterate and print each element of the array.
IntStream.of(values)
            .mapToObj(i -> Integer.toUnsignedString(i, 16))
            .forEach(System.out::println);

is an alternative (clearer IMO) to Arrays.stream().

Hi you can convert array to list and make use of lambda as below using new forEach method.

int[] values = new int[16];
List<Integer> list = Arrays.asList(values);
list.forEach(n -> System.out.println(n));

For simply printing integer, we don't need to map to any new object

Arrays.stream(arrInt1)            
      .forEach(i ->{
          System.out.print(i);
          System.out.print("\t");
      });

If you want to print given String[] as space separated between each element e.g.

String[] namesArray= new String[]{
"sam","ram","bam"};

as

sam ram bam

you can use this code

Arrays.stream(stringArray).map(stringElement ->  stringElement+” ”).forEach(System.out :: print);

and in case if you want to print int[] with space between elements things get slightly trickier as you need to convert int to String and then add space

int[] intArray= new int[]{
1,2,3,4};

as

1 2 3 4

you can use below code

Arrays.stream(intArray).mapToObject(intElement -> Integer.toUnsignedString(intElement) + “ ”).forEach(System.out :: print);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top