Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Java's lambda expressions to print an array?

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));
}
like image 997
Victor Lyuboslavsky Avatar asked Apr 27 '14 14:04

Victor Lyuboslavsky


People also ask

Can you use lambda expression array?

An array is a fixed size element of the same type. The lambda expressions can also be used to initialize arrays in Java.

How do I print a list in lambda expression?

// Create a list from a String array List list = new ArrayList(); String[] strArr = { "Chris", "Raju", "Jacky" }; for( int i = 0; i < strArr. length; i++ ) { list. add( strArr[i]); } // // Print the key and value of Map using Lambda expression // list. forEach((value) -> {System.

What does Java's lambda expression allow you to do?

Lambda expression is a new and important feature of Java which was included in Java SE 8. It provides a clear and concise way to represent one method interface using an expression. It is very useful in collection library. It helps to iterate, filter and extract data from collection.

How can I print an array in Java?

We cannot print array elements directly in Java, you need to use Arrays. toString() or Arrays. deepToString() to print array elements. Use toString() method if you want to print a one-dimensional array and use deepToString() method if you want to print a two-dimensional or 3-dimensional array etc.


2 Answers

Arrays.stream(values)
      .mapToObj(i -> Integer.toUnsignedString(i, 16))
      .forEach(System.out::println);
like image 62
JB Nizet Avatar answered Oct 07 '22 13:10

JB Nizet


String[] nums = {"three","two","one"};
Arrays.stream(nums).forEach(num -> System.out.println(num));
like image 23
sakumar Avatar answered Oct 07 '22 13:10

sakumar