Skip to content
Advertisement

How to print List of String array array using lambda in Java [closed]

This is my code:

List<String[]> salaries = getSalariesByMonth();

//I am using the old way to print the data
for (String[] obj : rates) {
    System.out.println("User name: "obj[0]+"--"+"Salary: "+obj[1]);   //obj[0] is NAME,  obj[1] is SALARY
}

//I am trying to use this way to print the data but unable to do so.
salaries.forEach(s-> System.out.println("print NAME and SALARY"));

How to print the List that contains String array using Lambda. Thank you in advance.

Advertisement

Answer

To convert a for-each loop into a forEach call the general pattern is:

for (final var x : xs) {
  statements;
}
// becomes:
xs.forEach(x -> { statements; });
// with a single statement, braces are optional:
xs.forEach(x -> statement);

A lambda of the form (x, y) -> { statements; } is mostly equivalent to a method of the form:

… yourMethod(final … x, final … y) {
  statements;
}

Return type and parameter type are inferred automatically by the compiler when a lambda is encountered.


So in your case that would be:

salaries.forEach(obj -> System.out.println("User name: "+obj[0]+"--"+"Salary: "+obj[1]));

You could also use streams to first map each object to a string representation and then output each item in a terminal operation:

salaries.stream()
        .map(obj -> "User name: "+obj[0]+"--"+"Salary: "+obj[1])
        .forEach(s -> System.out.println(s));

Since System.out.println expects exactly one argument which matches the lambda argument, it could be replaced with a method reference, which can be more readable in some cases: .forEach(System.out::println)

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement