Home java How to get a string array with Stream API?

How to get a string array with Stream API?

Author

Date

Category

There is a following method:

public static list & lt; string & gt; GetMessageOfbindingResult (BindingResult Result) {
  RETURN RESULT.GETFIELDERRORS (). Stream ()
      .map (Fe - & gt; string.format ("[% s]% s", Fe.GetField (), Fe.GetDefaultMessage ()))
      .collect (collectors.tolist ());
}

There is a need to return an array of String [] instead of the list LIST & LT; String & GT; . In Stream API there is a toarray () terminal operation, but it returns an Object array. So far I did like this:

Public Stating String [] GetMessagesOFBindingResult (BindingResult Result) {
    List & LT; Fielderror & GT; errors = result.getfielderrors ();
    String [] Messages = New String [Errors.size ()];
    For (int i = 0; i & lt; errors.size (); i ++) {
      Messages [i] = String.Format ("[% s]% s", errors.get (i) .getfield (), errors.get (i) .getDefaultMessage ());
    }
    Return Messages;
  }

But it seems to me that the desired array can be obtained easier, without creating a heap of intermediate lists.

Is there any opportunity to get the array string [] with Stream API?


Answer 1, Authority 100%

If Stream API will offer so

Public Static Void Main (String [] Args) {
  List & lt; String & GT; List = New ArrayList & LT; & GT; ();
  List.ADD ("String1");
  List.add ("String2");
  List.add ("String3");
  List.Add ("String4");
  String [] Result = List.Stream (). Collectors.Tolist ()). Toarray (New String [0]);
  For (String String: Result) {
   System.Out.printLN (String);
  }
 }

And if not, so

Public Static Void Main (String [] Args) {
  List & lt; String & GT; List = New ArrayList & LT; & GT; ();
  List.ADD ("String1");
  List.add ("String2");
  List.add ("String3");
  List.Add ("String4");
  String [] Result = List.ToArray (New String [0]);
  For (String String: Result) {
   System.Out.printLN (String);
  }
 }

the idea of ​​both one and the same use TOARRAY

In your case it will be so

Public Static String [] GetMessageOfBindingResult (BindingResult Result) {
  RETURN RESULT.GETFIELDERRORS (). Stream ()
      .map (Fe - & gt; string.format ("[% s]% s", Fe.GetField (), Fe.GetDefaultMessage ()))
      .collect (Collectors.Tolist ()). Toarray (New String [0]);
}

Answer 2, Authority 33%

You can do, for example, so:

string [] strings = intstream
  .range (5, 100)
  .Boxed ()
  .map (String :: Valueof)
  .toarray (String [] :: New);

Make I took Stream from Integer just as an example. Next, we transform everything into the string and last line we say that we need an array.

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions