Java MessageFormat Null Values - java

What is the best way to treat null values in Java MessageFormat
MessageFormat.format("Value: {0}",null);
=> Value: null
but actually a "Value: " would be nice.
Same with date
MessageFormat.format("Value: {0,date,medium}",null);
=> Value: null
a "Value: " whould be much more appreciated.
Is there any way to do this? I tried choice
{0,choice,null#|notnull#{0,date,dd.MM.yyyy – HH:mm:ss}}
which results in invalid choice format, what is correct to check for "null" or "not null"?

MessageFormat is only null-tolerant; that is, it will handle a null argument. If you want to have a default value appear instead of something if the value you're working with is null, you have two options:
You can either do a ternary...
MessageFormat.format("Value: {0}", null == value ? "" : value));
...or use StringUtils.defaultIfBlank() from commons-lang instead:
MessageFormat.format("Value: {0}", StringUtils.defaultIfBlank(value, ""));

Yes, you cant. Look at javadoc. Unfortunately, it dind't work with NULL.
Try use optional
Optional.ofNullable(value).orElse(0)
Or see example how to use ChoiceFormat and MessageFormat.
For more sophisticated patterns, you can use a ChoiceFormat to produce correct forms for singular and plural:
MessageFormat form = new MessageFormat("The disk \"{1}\" contains {0}.");
double[] filelimits = {0,1,2};
String[] filepart = {"no files","one file","{0,number} files"};
ChoiceFormat fileform = new ChoiceFormat(filelimits, filepart);
form.setFormatByArgumentIndex(0, fileform);
int fileCount = 1273;
String diskName = "MyDisk";
Object[] testArgs = {new Long(fileCount), diskName};
System.out.println(form.format(testArgs));
The output with different values for fileCount:
The disk "MyDisk" contains no files.
The disk "MyDisk" contains one file.
The disk "MyDisk" contains 1,273 files.
You can create the ChoiceFormat programmatically, as in the above example, or by using a pattern. See ChoiceFormat for more information.
form.applyPattern(
"There {0,choice,0#are no files|1#is one file|1

I need that now in my generator class by a mask.
Reason:
User can save mask with multiple types say "{0} {1,number,000} {2,date,MMyyyy}. And user have data where can be nulls. For result i use MessageFormat class. And want empty string without default 'null' text.
Null check is not that easy, because it will means replace pattern that is used for many records (not just one). And default empty value don't exists for number or date.
So if someone still needs solution. I give my.
Add this methods/classes (I have all in one class)
private static Object[] replaceNulls2NullValues( Object[] values ) {
for ( int i = 0; i < values.length; i++ )
if ( values[i] == null )
values[i] = NullFormatValue.NULL_FORMAT_VALUE;
return values;
}
private static MessageFormat modifyFormaterFormats( MessageFormat formater ) {
formater.setFormats( Arrays.stream( formater.getFormats() ).map( ( f ) -> ( f != null ) ? new NullHandlingFormatWrapper( f ) : null ).toArray( ( l ) -> new Format[l] ) );
return formater;
}
private static final class NullFormatValue {
static final Object NULL_FORMAT_VALUE = new NullFormatValue();
private NullFormatValue() {
}
#Override
public String toString() {
return "";
}
}
private static class NullHandlingFormatWrapper extends Format {
protected Format wrappedFormat;
public NullHandlingFormatWrapper( Format format ) {
wrappedFormat = format;
}
#Override
public StringBuffer format( Object obj, StringBuffer toAppendTo, FieldPosition pos ) {
if ( !( obj instanceof NullFormatValue ) )
wrappedFormat.format( obj, toAppendTo, pos );
return toAppendTo;
}
#Override
public Object parseObject( String source, ParsePosition pos ) {
return wrappedFormat.parseObject( source, pos );
}
}
and for result call
modifyFormaterFormats( new MessageFormat( pattern ) ).format( replaceNulls2NullValues( parameters ) );

Related

How to efficiently check if read line from Buffered reader contains a string from an enum list

I am a computer science university student working on my first 'big' project outside of class. I'm attempting to read through large text files (2,000 - 3,000 lines of text), line by line with buffered reader. When a keyword from a list of enums is located, I want it to send the current line from buffered reader to its appropriate method to be handled appropriatley.
I have a solution, but I have a feeling in my gut that there is a much better way to handle this situation. Any suggestions or feedback would be greatly appreciated.
Current Solution
I am looping through the the list of enums, then checking if the current enum's toString return is in the current line from buffered reader using the String.contains method.
If the enum is located, the enum is used in a switch statement for the appropriate method call. (I have 13 total cases just wanted to keep the code sample short).
try (BufferedReader reader = new BufferedReader(new FileReader(inputFile.getAbsoluteFile()))){
while ((currentLine = reader.readLine()) != null) {
for (GameFileKeys gameKey : GameFileKeys.values()) {
if (currentLine.contains(gameKey.toString())) {
switch (gameKey) {
case SEAT -> seatAndPlayerAssignment(currentTableArr, currentLine);
case ANTE -> playerJoinLate(currentLine);
}
}
}
}
}
Previous Solution
Originally, I had a nasty list of if statements checking if the current line contained one of the keywords and then handled it appropriatley. Clearly that is far from optimal, but my gut tells me that my current solution is also less than optimal.
try (BufferedReader reader = new BufferedReader(new FileReader(inputFile.getAbsoluteFile()))){
while ((currentLine = reader.readLine()) != null) {
if(currentLine.contains(GameFileKey.SEAT){
seatAndPlayerAssignment(currentTableArr, currentLine);
}
else if(currentLine.contains(GameFileKey.ANTE){
playerJoinLate(currentLine);
}
}
}
Enum Class
In case you need this, or have any general feedback for how I'm implementing my enums.
public enum GameFileKeys {
ANTE("posts ante"),
SEAT("Seat ");
private final String gameKey;
GameFileKeys(String str) {
this.gameKey = str;
}
#Override
public String toString() {
return gameKey;
}
}
I cannot improve over the core of your code: the looping on values() of the enum, performing a String#contains for each enum object’s string, and using a switch. I can make a few minor suggestions.
I suggest you not override the toString method on your enum. The Object#toString method is generally best used only for debugging and logging, not logic or presentation.
Your string passed to constructor of the enum is likely similar to the idea of a display name commonly seen in such enums. The formal enum name (all caps) is used internally within Java, while the display name is used for display to the user or exchanged with external systems. See the Month and DayOfWeek enums as examples offering a getDisplayName method.
Also, an enum should be named in the singular. This avoids confusion with any collections of the enum’s objects.
By the way, looks like you have a stray SPACE in your second enum's argument.
At first I thought it would help to have a list of all the display names, and a map of display name to enum object. However, in the end neither is needed for your purpose. I kept those as they might prove interesting.
public enum GameFileKey
{
ANTE( "posts ante" ),
SEAT( "Seat" );
private String displayName = null;
private static final List < String > allDisplayNames = Arrays.stream( GameFileKey.values() ).map( GameFileKey :: getDisplayName ).toList();
private static final Map < String, GameFileKey > mapOfDisplayNameToGameFileKey = Arrays.stream( GameFileKey.values() ).collect( Collectors.toUnmodifiableMap( GameFileKey :: getDisplayName , Function.identity() ) );
GameFileKey ( String str ) { this.displayName = str; }
public String getDisplayName ( ) { return this.displayName; }
public static GameFileKey forDisplayName ( final String displayName )
{
return
Objects.requireNonNull(
GameFileKey.mapOfDisplayNameToGameFileKey.get( displayName ) ,
"None of the " + GameFileKey.class.getCanonicalName() + " enum objects has a display name of: " + displayName + ". Message # 4dcefee2-4aa2-48cf-bf66-9a4bde02ac37." );
}
public static List < String > allDisplayNames ( ) { return GameFileKey.allDisplayNames; }
}
You can use a stream of the lines of your file being processed. Just FYI, not necessarily better than your code.
public class Demo
{
public static void main ( String[] args )
{
Demo app = new Demo();
app.demo();
}
private void demo ( )
{
try
{
Path path = Demo.getFilePathToRead();
Stream < String > lines = Files.lines( path );
lines.forEach(
line -> {
for ( GameFileKey gameKey : GameFileKey.values() )
{
if ( line.contains( gameKey.getDisplayName() ) )
{
switch ( gameKey )
{
case SEAT -> this.seatAndPlayerAssignment( line );
case ANTE -> this.playerJoinLate( line );
}
}
}
}
);
}
catch ( IOException e )
{
throw new RuntimeException( e );
}
}
private void playerJoinLate ( String line )
{
System.out.println( "line = " + line );
}
private void seatAndPlayerAssignment ( String line )
{
System.out.println( "line = " + line );
}
public static Path getFilePathToRead ( ) throws IOException
{
Path tempFile = Files.createTempFile( "bogus" , ".txt" );
Files.write( tempFile , "apple\nSeat\norange\nposts ante\n".getBytes() );
return tempFile;
}
}
When run:
line = Seat
line = posts ante

how to fetch correctly the data from the a table in mysql which contains Italian,Japanese and Russian characters

I have a table with UTF8 charset. The columns are considered utf8_general_ci. I am reading the data using prepared statement but they are not shown correctly. The data inside the table is not readable too. I need to write a code in a way that they are human readable. I have tested many methods which all failed.
For the Connection property I used "?useUnicode=true&characterEncoding=UTF8";
String city=resultset.getString("city");
byte[] data = city.getBytes();
String valueCity = new String(data, "UTF-8"); // Or String valueCity = new String(data, StandardCharsets.UTF_8);
I see something like "&#21517 ; & #21476 ;& #23627; & #24066;" in my table but I need to read or write them like 名古屋市.
Any suggestions that I may handle this problem which is a pain on my neck?
thanks a million in advance
Maybe it is resultset.getString("city") what is your problem here. You already receive the data as a string. The byte representation of that string is likely not utf-8. What's the type of resultset?
Are you sure you opened your database connection with characterEncoding=utf8? You need to set connectionProperties="useUnicode=yes;characterEncoding=utf8;"
Stackoverflow
Something, not MySQL, is generating "html entities" such as 名. Find where those are coming from and undo it.
Since those entities are probably already stored in the table, that needs to be undone, too.
The html entities should render correctly in any browser. Are you trying to use them in some other context?
It might help to check the resultset.getBytes(..) instead of getString first
Finally I found the code:
public static String unescapeXML( final String xml )
{
Pattern xmlEntityRegex = Pattern.compile( "&(#?)([^;]+);" );
// Matcher requires a StringBuffer instead of a StringBuilder
StringBuffer unescapedOutput = new StringBuffer( xml.length() );
Matcher m = xmlEntityRegex.matcher( xml );
Map<String,String> builtinEntities = null;
String entity;
String hashmark;
String ent;
int code;
while ( m.find() ) {
ent = m.group(2);
hashmark = m.group(1);
if ( (hashmark != null) && (hashmark.length() > 0) ) {
code = Integer.parseInt( ent );
entity = Character.toString( (char) code );
} else {
//must be a non-numerical entity
if ( builtinEntities == null ) {
builtinEntities = buildBuiltinXMLEntityMap();
}
entity = builtinEntities.get( ent );
if ( entity == null ) {
//not a known entity - ignore it
entity = "&" + ent + ';';
}
}
m.appendReplacement( unescapedOutput, entity );
}
m.appendTail( unescapedOutput );
return unescapedOutput.toString();
}
private static Map<String,String> buildBuiltinXMLEntityMap()
{
Map<String,String> entities = new HashMap<String,String>(10);
entities.put( "lt", "<" );
entities.put( "gt", ">" );
entities.put( "amp", "&" );
entities.put( "apos", "'" );
entities.put( "quot", "\"" );
return entities;
}

String converting issure

ive got a problem with string conversion.
I am trying to implement a system where numbers (BigDecimal) are printed to the screen when they are updated.
Therefore i created a subclass of BigDecimal (dpzahl) to detect the updated number and send a updaterequest to the ui.
So basically: i save the string (text) from String.xml. example:
"value of %s: %s"
and i save the references of the arguments in argument.
these references can be Strings, SpannableStrings or dpzahl's.
But while preparing the string.format ive got a problem:
Log.d(MainActivity.LOGTAG,"update request is executed");
final Object[] ARGS = new CharSequence[argumente.size()]; //to be put into the formater
int i = 0;
for(Object ooo: arguments) { // private ArrayList<Object> arguments; is a class variable
if (ooo instanceof dpzahl) { // dpzahl extends BigDecimal to get the number i want to format
ARGS[i] = haupt.format_bigies(((dpzahl) ooo).get()); //get the formated string
Log.d(MainActivity.LOGTAG,"number print:"+ARGS[i].toString());
}if(ooo instanceof SpannableString){ //some other arguments i may need in the string.format argument list
ARGS[i] = ((SpannableString)ooo);
}else{ //for any other object, mostly Strings
ARGS[i] = ooo.toString();
}
if (ooo instanceof dpzahl) { //only for debugprint
Log.d(MainActivity.LOGTAG,"loopvalue dpzahl:"+ARGS[i].toString());
}
Log.d(MainActivity.LOGTAG,"loopvalue:"+ARGS[i].toString());
i++;
}
for(Object ooo: ARGS) { //only for debugprint
if(ooo instanceof String){
Log.d(MainActivity.LOGTAG, "againarg Stirng:" + ((String)ooo));
}else if(ooo instanceof SpannableString) {
Log.d(MainActivity.LOGTAG, "againarg SpannableString:" + ((SpannableString)ooo).toString());
}
Log.d(MainActivity.LOGTAG, "againarg Object:" + ooo.toString());
}
sicht.post(new Runnable() {
#Override
public void run() {
Log.d(MainActivity.LOGTAG,"allargs:"+ Arrays.toString(ARGS));
view.setText(SpanFormatter.format(text, ARGS));//Copyright © 2014 George T. Steel, replace string.format for SpannableString
view.invalidate();//the linked TextView
}
});
If i put in the SpannableString "testvalue" and the BigDecimal expression for 4 the output is
output:
update request is executed
loopvalue:testvalue
formated BigDecimal:4
number print:4
loopvalue dpzahl:4.000000000
loopvalue:4.000000000
againarg SpannableString:testvalue
againarg Object:testvalue
againarg Stirng:4.000000000
againarg Object:4.000000000
allargs:[testvalue , 4.000000000]
so the TextView String should be "value of testvalue: 4" but it is "value of testvalue: 4.000000000"
So why have the Value of ARGS[1] first the value of String "4" and later the value "4.000000000" before it is passed to the formater?
ps: the problem appears when i implemented the SpannableString to the formater, before this, the line
final Object[] ARGS = new CharSequence[argumente.size()];
was
final Object[] ARGS = new String[argumente.size()];
and all work fine. But SpannableString does not extend Strings so i need the next upper lowest common denominator which is CharSequence.
pp: using
final Object[] ARGS = new Object[argumente.size()];
does not help.
Change
if(ooo instanceof SpannableString)
to
else if(ooo instanceof SpannableString)

Logical flaw: if List<String> is null return input else print function output

In my code I call this method, as a preprocessing step to 'stem' words:
public void getStem(String word)
{
WordnetStemmer stem = new WordnetStemmer( dict );
List<String> stemmed_words = stem.findStems(word, POS.VERB);
System.out.println( stemmed_words.get(0) );
}
Usually everything is good if it gets a normal word (I'm using the Java Wordnet Interface to handle the stemming). The thing is--> I don't always get a normal word, somethings I get things along the lines of isa which is a conjunction of is and a. In such a case that method will return null and my program will crash. How can I defend against this?
This is how I call that code:
public Sentence(String verb, String object, String subject ) throws IOException
{
WordNet wordnet = new WordNet();
this.verb = verb;
this.object = object;
this.subject = subject;
wordnet.getStem( verb );
}
Eventually I want that to read:
this.verb = wordnet.getStem( verb );
I once heard about doing something with null objects, is that applicable here?
I tried this but it didn't work, but I want to do something like this:
public void getStem(String word)
{
WordnetStemmer stem = new WordnetStemmer( dict );
List<String> stemmed_words = stem.findStems(word, POS.VERB);
if( stemmed_words != null)
System.out.println( stemmed_words.get(0) );
else
System.out.println( word );
}
This is the output:
prevent
contain
contain
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0
at java.util.Collections$EmptyList.get(Collections.java:4454)
at inference_learner.WordNet.getStem(WordNet.java:76)
at inference_learner.Sentence.<init>(Sentence.java:23)
at inference_learner.RegEx.match_regex_patterns(RegEx.java:33)
at inference_learner.ReadFile.readFile(ReadFile.java:30)
at inference_learner.Main.main(Main.java:38)
That won't work because the List is not null, the List is empty.
You have to do the check like this if (stemmed_words.size() > 0)
try
if( stemmed_words != null && stemmed_words.size() > 0))
System.out.println( stemmed_words.get(0) );
else
System.out.println( word );
}

Java: Get last element after split

I am using the String split method and I want to have the last element.
The size of the Array can change.
Example:
String one = "Düsseldorf - Zentrum - Günnewig Uebachs"
String two = "Düsseldorf - Madison"
I want to split the above Strings and get the last item:
lastone = one.split("-")[here the last item] // <- how?
lasttwo = two.split("-")[here the last item] // <- how?
I don't know the sizes of the arrays at runtime :(
You could use lastIndexOf() method on String
String last = string.substring(string.lastIndexOf('-') + 1);
Save the array in a local variable and use the array's length field to find its length. Subtract one to account for it being 0-based:
String[] bits = one.split("-");
String lastOne = bits[bits.length-1];
Caveat emptor: if the original string is composed of only the separator, for example "-" or "---", bits.length will be 0 and this will throw an ArrayIndexOutOfBoundsException. Example: https://onlinegdb.com/r1M-TJkZ8
You can use the StringUtils class in Apache Commons:
StringUtils.substringAfterLast(one, "-");
using a simple, yet generic, helper method like this:
public static <T> T last(T[] array) {
return array[array.length - 1];
}
you can rewrite:
lastone = one.split("-")[..];
as:
lastone = last(one.split("-"));
String str = "www.anywebsite.com/folder/subfolder/directory";
int index = str.lastIndexOf('/');
String lastString = str.substring(index +1);
Now lastString has the value "directory"
Gathered all possible ways together!!
By using lastIndexOf() & substring() methods of Java.lang.String
// int firstIndex = str.indexOf( separator );
int lastIndexOf = str.lastIndexOf( separator );
String begningPortion = str.substring( 0, lastIndexOf );
String endPortion = str.substring( lastIndexOf + 1 );
System.out.println("First Portion : " + begningPortion );
System.out.println("Last Portion : " + endPortion );
split()Java SE 1.4. Splits the provided text into an array.
String[] split = str.split( Pattern.quote( separator ) );
String lastOne = split[split.length-1];
System.out.println("Split Array : "+ lastOne);
How to split String before first comma?
Java 8 sequential ordered stream from an array.
String firstItem = Stream.of( split )
.reduce( (first,last) -> first ).get();
String lastItem = Stream.of( split )
.reduce( (first,last) -> last ).get();
System.out.println("First Item : "+ firstItem);
System.out.println("Last Item : "+ lastItem);
Apache Commons Langjar « org.apache.commons.lang3.StringUtils
String afterLast = StringUtils.substringAfterLast(str, separator);
System.out.println("StringUtils AfterLast : "+ afterLast);
String beforeLast = StringUtils.substringBeforeLast(str, separator);
System.out.println("StringUtils BeforeLast : "+ beforeLast);
String open = "[", close = "]";
String[] groups = StringUtils.substringsBetween("Yash[777]Sam[7]", open, close);
System.out.println("String that is nested in between two Strings "+ groups[0]);
Guava: Google Core Libraries for Java. « com.google.common.base.Splitter
Splitter splitter = Splitter.on( separator ).trimResults();
Iterable<String> iterable = splitter.split( str );
String first_Iterable = Iterables.getFirst(iterable, "");
String last_Iterable = Iterables.getLast( iterable );
System.out.println(" Guava FirstElement : "+ first_Iterable);
System.out.println(" Guava LastElement : "+ last_Iterable);
Scripting for the Java Platform « Run Javascript on the JVM with Rhino/Nashorn
Rhino « Rhino is an open-source implementation of JavaScript written entirely in Java. It is typically embedded into Java applications to provide scripting to end users. It is embedded in J2SE 6 as the default Java scripting engine.
Nashorn is a JavaScript engine developed in the Java programming language by Oracle. It is based on the Da Vinci Machine and has been released with Java 8.
Java Scripting Programmer's Guide
public class SplitOperations {
public static void main(String[] args) {
String str = "my.file.png.jpeg", separator = ".";
javascript_Split(str, separator);
}
public static void javascript_Split( String str, String separator ) {
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("JavaScript");
// Script Variables « expose java objects as variable to script.
engine.put("strJS", str);
// JavaScript code from file
File file = new File("E:/StringSplit.js");
// expose File object as variable to script
engine.put("file", file);
try {
engine.eval("print('Script Variables « expose java objects as variable to script.', strJS)");
// javax.script.Invocable is an optional interface.
Invocable inv = (Invocable) engine;
// JavaScript code in a String
String functions = "function functionName( functionParam ) { print('Hello, ' + functionParam); }";
engine.eval(functions);
// invoke the global function named "functionName"
inv.invokeFunction("functionName", "function Param value!!" );
// evaluate a script string. The script accesses "file" variable and calls method on it
engine.eval("print(file.getAbsolutePath())");
// evaluate JavaScript code from given file - specified by first argument
engine.eval( new java.io.FileReader( file ) );
String[] typedArray = (String[]) inv.invokeFunction("splitasJavaArray", str );
System.out.println("File : Function returns an array : "+ typedArray[1] );
ScriptObjectMirror scriptObject = (ScriptObjectMirror) inv.invokeFunction("splitasJavaScriptArray", str, separator );
System.out.println("File : Function return script obj : "+ convert( scriptObject ) );
Object eval = engine.eval("(function() {return ['a', 'b'];})()");
Object result = convert(eval);
System.out.println("Result: {}"+ result);
// JavaScript code in a String. This code defines a script object 'obj' with one method called 'hello'.
String objectFunction = "var obj = new Object(); obj.hello = function(name) { print('Hello, ' + name); }";
engine.eval(objectFunction);
// get script object on which we want to call the method
Object object = engine.get("obj");
inv.invokeMethod(object, "hello", "Yash !!" );
Object fileObjectFunction = engine.get("objfile");
inv.invokeMethod(fileObjectFunction, "hello", "Yashwanth !!" );
} catch (ScriptException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public static Object convert(final Object obj) {
System.out.println("\tJAVASCRIPT OBJECT: {}"+ obj.getClass());
if (obj instanceof Bindings) {
try {
final Class<?> cls = Class.forName("jdk.nashorn.api.scripting.ScriptObjectMirror");
System.out.println("\tNashorn detected");
if (cls.isAssignableFrom(obj.getClass())) {
final Method isArray = cls.getMethod("isArray");
final Object result = isArray.invoke(obj);
if (result != null && result.equals(true)) {
final Method values = cls.getMethod("values");
final Object vals = values.invoke(obj);
System.err.println( vals );
if (vals instanceof Collection<?>) {
final Collection<?> coll = (Collection<?>) vals;
Object[] array = coll.toArray(new Object[0]);
return array;
}
}
}
} catch (ClassNotFoundException | NoSuchMethodException | SecurityException
| IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
}
}
if (obj instanceof List<?>) {
final List<?> list = (List<?>) obj;
Object[] array = list.toArray(new Object[0]);
return array;
}
return obj;
}
}
JavaScript file « StringSplit.js
// var str = 'angular.1.5.6.js', separator = ".";
function splitasJavaArray( str ) {
var result = str.replace(/\.([^.]+)$/, ':$1').split(':');
print('Regex Split : ', result);
var JavaArray = Java.to(result, "java.lang.String[]");
return JavaArray;
// return result;
}
function splitasJavaScriptArray( str, separator) {
var arr = str.split( separator ); // Split the string using dot as separator
var lastVal = arr.pop(); // remove from the end
var firstVal = arr.shift(); // remove from the front
var middleVal = arr.join( separator ); // Re-join the remaining substrings
var mainArr = new Array();
mainArr.push( firstVal ); // add to the end
mainArr.push( middleVal );
mainArr.push( lastVal );
return mainArr;
}
var objfile = new Object();
objfile.hello = function(name) { print('File : Hello, ' + name); }
JavaScript Array constructor or array literal.
With Guava:
final Splitter splitter = Splitter.on("-").trimResults();
assertEquals("Günnewig Uebachs", Iterables.getLast(splitter.split(one)));
assertEquals("Madison", Iterables.getLast(splitter.split(two)));
Splitter, Iterables
Since he was asking to do it all in the same line using split so i suggest this:
lastone = one.split("-")[(one.split("-")).length -1]
I always avoid defining new variables as far as I can, and I find it a very good practice
You mean you don't know the sizes of the arrays at compile-time? At run-time they could be found by the value of lastone.length and lastwo.length .
Also you can use java.util.ArrayDeque
String last = new ArrayDeque<>(Arrays.asList("1-2".split("-"))).getLast();
In java 8
String lastItem = Stream.of(str.split("-")).reduce((first,last)->last).get();
I guess you want to do this in i line. It is possible (a bit of juggling though =^)
new StringBuilder(new StringBuilder("Düsseldorf - Zentrum - Günnewig Uebachs").reverse().toString().split(" - ")[0]).reverse()
tadaa, one line -> the result you want (if you split on " - " (space minus space) instead of only "-" (minus) you will loose the annoying space before the partition too =^) so "Günnewig Uebachs" instead of " Günnewig Uebachs" (with a space as first character)
Nice extra -> no need for extra JAR files in the lib folder so you can keep your application light weight.

Categories