22
33import java .util .LinkedHashMap ;
44import java .util .Map ;
5+ import java .util .function .BiConsumer ;
56
67public abstract class AbstractOptions < T extends AbstractOptions < T > > implements Options < T >
78{
89 final LinkedHashMap < String , Object > theOptions = new LinkedHashMap <>();
910
1011 protected AbstractOptions ( T that )
1112 {
12- that . theOptions .forEach ( theOptions :: put );
13+ theOptions .putAll ( that . theOptions );
1314 }
1415
1516 public AbstractOptions ()
@@ -27,14 +28,19 @@ protected T append( final T additionalOptions )
2728 return ( T ) this ;
2829
2930 T concat = copyOrThis ();
30- additionalOptions .theOptions .forEach ( concat .theOptions ::put );
31+ additionalOptions .theOptions .forEach ( ( k , v ) -> {
32+ // NB remove existing key for ordering for appended options
33+ concat .theOptions .remove ( k );
34+ concat .theOptions .put ( k , v );
35+ } );
3136 return concat ;
3237 }
3338
3439 @ Override
3540 public T add ( final String key , final Object value )
3641 {
3742 final T copy = copyOrThis ();
43+ // NB remove existing key for ordering for appended options
3844 copy .theOptions .remove ( key );
3945 copy .theOptions .put ( key , value );
4046 return copy ;
@@ -57,4 +63,62 @@ public String toString()
5763 sb .append ( "}" );
5864 return sb .toString ();
5965 }
66+
67+ protected abstract class AbstractValues implements Values
68+ {
69+ public void forEach ( BiConsumer < String , Object > action )
70+ {
71+ theOptions .forEach ( action );
72+ }
73+
74+ @ Override
75+ public String toString ()
76+ {
77+ final ValuesToString sb = new ValuesToString ();
78+ forEach ( sb );
79+ return sb .toString ();
80+ }
81+
82+ @ Override
83+ public < T > T value ( final String key , final T defaultValue )
84+ {
85+ @ SuppressWarnings ( "unchecked" )
86+ final T value = ( T ) theOptions .get ( key );
87+ return value == null ? defaultValue : value ;
88+ }
89+ }
90+
91+ protected class ValuesToString implements BiConsumer < String , Object >
92+ {
93+ private final StringBuilder sb ;
94+
95+ private boolean first ;
96+
97+ public ValuesToString ()
98+ {
99+ sb = new StringBuilder ().append ( "{" );
100+ first = true ;
101+ }
102+
103+ @ Override
104+ public String toString ()
105+ {
106+ sb .append ( "}" );
107+ return sb .toString ();
108+ }
109+
110+ @ Override
111+ public void accept ( final String key , final Object value )
112+ {
113+ if ( first )
114+ first = false ;
115+ else
116+ sb .append ( ", " );
117+ sb .append ( key );
118+ sb .append ( " = " );
119+ sb .append ( value );
120+ if ( !theOptions .containsKey ( key ) )
121+ sb .append ( " [default]" );
122+ }
123+ }
60124}
0 commit comments