Java string result to string

Converting «Stream» to «String» in java8 to combine group of strings in a stream

In java 8, there is method joining(), Which is the part of Collectors class. You have to join this string using Collectors.joining() .

String result = Stream.of("do", "re", "ma", "po", "fa", "si") .filter(str -> str.length() > 1) .collect(Collectors.joining()); 
String result= Stream.of("do","re","ma","po","fa","si") .filter(str -> str.length() > 1) .peek(System.out::println) .collect(Collectors.joining()); 

Do you looking for something like this?

 String result = Stream.of("do","re","ma","po","fa","si"). collect(Collectors.joining("")); System.out.println(result); 
 String result = Stream.of("do", "re", "ma", "po", "fa", "si") .filter(str -> str.length() > 1) .peek(System.out::println) .collect(Collectors.joining("")); System.out.println(result); 
do re ma po fa si doremapofasi 

You misunderstand the mechanisms behind the Stream API.

A stream pipeline consists of a source (which might be an array, a collection, a generator function, an I/O channel, etc), zero or more intermediate operations (which transform a stream into another stream, such as filter(Predicate)), and a terminal operation (which produces a result or side-effect, such as count() or forEach(Consumer)). Streams are lazy ; computation on the source data is only performed when the terminal operation is initiated , and source elements are consumed only as needed.

The main conclusion:

Operations on the data in the pipeline will be performed only if the terminal operation is initiated .

Stream without a terminal operation is perfectly valid from the compiler’s perspective of view. It will compile, but it’ll not be executed.

Читайте также:  Функция обновления страницы php

And what you have tried to print ( java.util.Spliterators$1Adapter@63961c42 ) isn’t a result, but the stream object itself.

To produce a result or side-effect Stream-pipeline must end with a terminal operation ( collect() , reduce() , count() , forEach() , findFirst() , findAny , anyMatch() — which commented out in your code). Note, that peek() is an intermediate operation and confuse it with forEach() . You can use peek() as many time as need, which can be useful for debugging purposes.

 public static void main(String[] args) < String result = getStream() .filter(str ->str.length() > 5 && str.length() < 8) .findFirst() // that will produce a single result that may or may not be present .orElseThrow(); // action for the case if result is not present System.out.println("Single result: " + result + "\n"); getStream() .filter(str ->str.contains("a")) .peek(System.out::println) // intermediate operation that will print every element that matches the first filter .filter(str -> str.length() > 8) .forEach(System.out::println); // terminal operation that prints every element remained after processing the pipeline > private static Stream getStream()
Single result: portum Ignoranti Ignoranti petat 

Источник

Java String Array to String

Java String Array to String

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Today we will look into how to convert Java String array to String. Sometimes we have to convert String array to String for specific requirements. For example; we want to log the array contents or we need to convert values of the String array to String and invoke other methods.

Java String Array to String

Most of the time we invoke toString() method of an Object to get the String representation. Let’s see what happens when we invoke toString() method on String array in java.

package com.journaldev.util; public class JavaStringArrayToString < public static void main(String[] args) < String[] strArr = new String[] ; String str = strArr.toString(); System.out.println("Java String array to String = "+str); > > 

java string array to string toString method call output

Below image shows the output produced by the above program. The reason for the above output is because toString() call on the array is going to Object superclass where it’s implemented as below.

Java String Array to String Example

So how to convert String array to String in java. We can use Arrays.toString method that invoke the toString() method on individual elements and use StringBuilder to create String.

public static String toString(Object[] a) < if (a == null) return "null"; int iMax = a.length - 1; if (iMax == -1) return "[]"; StringBuilder b = new StringBuilder(); b.append('['); for (int i = 0; ; i++) < b.append(String.valueOf(a[i])); if (i == iMax) return b.append(']').toString(); b.append(", "); >> 

We can also create our own method to convert String array to String if we have some specific format requirements. Below is a simple program showing these methods in action and output produced.

package com.journaldev.util; import java.util.Arrays; public class JavaStringArrayToString < public static void main(String[] args) < String[] strArr = new String[] < "1", "2", "3" >; String str = Arrays.toString(strArr); System.out.println("Java String array to String = " + str); str = convertStringArrayToString(strArr, ","); System.out.println("Convert Java String array to String = " + str); > private static String convertStringArrayToString(String[] strArr, String delimiter) < StringBuilder sb = new StringBuilder(); for (String str : strArr) sb.append(str).append(delimiter); return sb.substring(0, sb.length() - 1); >> 

convert string array to string in java

So if we use array toString() method, it returns useless data. Java Arrays class provide toString(Object[] objArr) that iterates over the elements of the array and use their toString() implementation to return the String representation of the array. That’s why when we use this function, we can see that it’s printing the array contents and it can be used for logging purposes. If you want to combine all the String elements in the String array with some specific delimiter, then you can use convertStringArrayToString(String[] strArr, String delimiter) method that returns the String after combining them.

Java Array to String Example

Now let’s extend our String array to String example to use with any other custom classes, here is the implementation.

package com.journaldev.util; import java.util.Arrays; public class JavaArrayToString < public static void main(String[] args) < A[] arr = < new A("1"), new A("2"), new A("3") >; // default toString() method System.out.println(arr.toString()); // using Arrays.toString() for printing object array contents System.out.println(Arrays.toString(arr)); // converting Object Array to String System.out.println(convertObjectArrayToString(arr, ",")); > private static String convertObjectArrayToString(Object[] arr, String delimiter) < StringBuilder sb = new StringBuilder(); for (Object obj : arr) sb.append(obj.toString()).append(delimiter); return sb.substring(0, sb.length() - 1); >> class A < private String name; public A(String name) < this.name = name; >@Override public String toString() < System.out.println("A toString() method called!!"); return this.name; >> 
[Lcom.journaldev.util.A;@7852e922 A toString() method called!! A toString() method called!! A toString() method called!! [1, 2, 3] A toString() method called!! A toString() method called!! A toString() method called!! 1,2,3 

So we looked at how to convert Java String array to String and then extended it to use with custom objects. That’s all for converting java array to String. You can checkout more core java examples from our GitHub Repository. Reference: Java Arrays toString API Doc

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases. Learn more about us

Источник

How to convert ResultSet to string in Java

I want to convert resultset to string. After that, I will use the string to write a html file.Course is a table contain courseid(String),name(String),prerequisites(String) connect database is ok. Here is my code and idea. Can you evaluate my idea or give me some better solution?

private static void printRecordFromCourse() throws SQLException < Connection dbConnection = null; Statement stmt = null; String printSQL = "SELECT * FROM course"; try < dbConnection = getDBConnection(); stmt = dbConnection.createStatement(); ResultSet rs=stmt.executeQuery(printSQL); while(rs.next())< //Retrieve by column name String courseid = rs.getString("courseid"); String name = rs.getString("name"); String prerequisites = rs.getString("prerequisites"); String result+ = ""+courseid+""+name+""+prerequisites""; > rs.close(); > catch (SQLException e) < System.out.println(e.getMessage()); >finally < if (stmt != null) < dbConnection.close(); >if (dbConnection != null) < dbConnection.close(); >> > 

Is there some error that you are getting with the above code? You can use a class — Course and use corresponding getter/setter methods to access/update the values

I wont recommend you calling toString directly on resultset. You should populate it in your Course class and define custom toString in your Course class which you can then call toString upon. Please ensure you add java tag to your question.

A ResultSet isn’t a string, or anything resembling one. Logically speaking it is an array of maps. You need to traverse it, getting column values for each row, and do whatever you need to do with those.

2 Answers 2

You could use an ArrayList and store the columns in there, such as:

List allRows = new ArrayList(); while(rs.next()) < String[] currentRow = new String[numberColumns]; for(int i = 1;i<=numberColumns;i++)< row[i-1]=rs.getString(i); >rows.add(row); > 

Your ArrayList now contains String arrays, where each array represents one row. Now you can simply transform the string array entries into strings, e.g. using Arrays.toString(allRows.get(i));

I have not tried your code, but it looks workable at a glance.

Design-wise, we usually want to separate database access from other logic.

And likely you will want to define a class Course to hold this data and your business logic that operates on that data. For example, you may choose to implement a toHtmlTableRow method on Course that generates the HTML source. (In a more complex or sophisticated environment, you might also want to move that HTML-generation functionality to another class.) Something like this:

class Course < String id, name, prereq; public Course ( String id , String name , String prereq ) < this.id = id; this.name = name; this.prereq = prereq; >public CharSequence toHtmlTableRow () < StringBuilder html = new StringBuilder(); html.append( "\n" ); html.append( "" + this.id + "" + this.name + "" + this.prereq + "\n" ); html.append( "\n" ); return html; > // Override `Object`. @Override public String toString () < return "Course< " + "id='" + id + '\'' + " | name='" + name + '\'' + " | prereq='" + prereq + '\'' + " >"; > > 

Here is a complete working example app. For the sake of this demo, I crammed it all into a single .java file. In real work, I would not.

This example uses the H2 Database Engine. This example makes an in-memory database that never gets written to storage, again because this is a mere example.

Note the use of the try-with-resource & AutoCloseable syntax found in newer versions of Java to simplify working with JDBC.

package com.basilbourque.example; import java.sql.*; import java.time.LocalDate; import java.time.ZoneId; import java.util.ArrayList; import java.util.List; import java.util.UUID; public class DbToText < public static void main ( String[] args ) < DbToText app = new DbToText(); app.doIt(); >private void doIt () < try < Class.forName( "org.h2.Driver" ); >catch ( ClassNotFoundException e ) < e.printStackTrace(); >List < Course >courses = new ArrayList(); try ( Connection conn = DriverManager.getConnection( "jdbc:h2:mem:db_to_text" ) ; Statement stmt = conn.createStatement() ; ) < String sql = "CREATE TABLE course_ ( \n" + " id_ VARCHAR NOT NULL PRIMARY KEY , \n" + " name_ VARCHAR NOT NULL , \n" + " prereq_ VARCHAR NOT NULL \n" + ");"; stmt.execute( sql ); // Insert row. sql = "INSERT INTO course_ ( id_ , name_ , prereq_ ) VALUES ( ? , ? , ? ) ;"; try ( PreparedStatement preparedStatement = conn.prepareStatement( sql ) ; ) < preparedStatement.setString( 1 , "C01" ); preparedStatement.setString( 2 , "Course 1" ); preparedStatement.setString( 3 , "None" ); preparedStatement.executeUpdate(); preparedStatement.setString( 1 , "C02" ); preparedStatement.setString( 2 , "Course 2" ); preparedStatement.setString( 3 , "C01" ); preparedStatement.executeUpdate(); preparedStatement.setString( 1 , "C03" ); preparedStatement.setString( 2 , "Course 3" ); preparedStatement.setString( 3 , "C02" ); preparedStatement.executeUpdate(); >// Query all. sql = "SELECT * FROM course_"; try ( ResultSet rs = stmt.executeQuery( sql ) ; ) < while ( rs.next() ) < //Retrieve by column name String "id_" ); String name = rs.getString( "name_" ); String prereq = rs.getString( "prereq_" ); // Instantiate a `Course` object for this data. Course c = new Course( id , name , prereq ); courses.add( c ); >> > catch ( SQLException e ) < e.printStackTrace(); >System.out.println( "List of courses: \n" + courses ); System.out.println( "Courses as HTML table rows: " ); for ( Course course : courses ) < System.out.println( course.toHtmlTableRow() ); >> class Course < String id, name, prereq; public Course ( String id , String name , String prereq ) < this.id = id; this.name = name; this.prereq = prereq; >public CharSequence toHtmlTableRow () < StringBuilder html = new StringBuilder(); html.append( "\n" ); html.append( "" + this.id + "" + this.name + "" + this.prereq + "\n" ); html.append( "\n" ); return html; > // Override `Object`. @Override public String toString () < return "Course< " + "id='" + id + '\'' + " | name='" + name + '\'' + " | prereq='" + prereq + '\'' + " >"; > > > 
List of courses: [Course< | name='Course 1' | prereq='None' >, Course< | name='Course 2' | prereq='C01' >, Course< | name='Course 3' | prereq='C02' >] Courses as HTML table rows: C01Course 1None  C02Course 2C01  C03Course 3C02  

Источник

Оцените статью