只是为了好玩:
import java.util.Comparator;
import java.util.List;
import java.util.SortedSet;
import java.util.TreeSet;
public class State
{
public static class KeyValuePair
{
private final String key;
private final String value;
public KeyValuePair( String key, String value )
{
super();
this.key = key;
this.value = value;
}
public String getKey()
{
return this.key;
}
public String getValue()
{
return this.value;
}
}
public boolean setState( List<KeyValuePair> pairs )
{
//
boolean happy = false;
//
final Comparator<KeyValuePair> comparator = new Comparator<KeyValuePair>()
{
@Override
public int compare( KeyValuePair o1, KeyValuePair o2 )
{
int compareTo = o1.getKey().compareTo( o2.getKey() );
if ( compareTo == 0 )
{
compareTo = o1.getValue().compareTo( o2.getValue() );
}
return compareTo;
}
};
final SortedSet<KeyValuePair> matchingKeyValuePairSet = new TreeSet<KeyValuePair>( comparator );
matchingKeyValuePairSet.add( new KeyValuePair( "hunger", "Y" ) );
matchingKeyValuePairSet.add( new KeyValuePair( "tired", "Y" ) );
matchingKeyValuePairSet.add( new KeyValuePair( "sad", "N" ) );
for ( KeyValuePair pair : pairs )
{
happy |= matchingKeyValuePairSet.contains( pair );
}
//
return happy;
}
}
JUnit 测试用例:
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.util.Arrays;
import java.util.List;
import org.junit.Test;
public class StateTest
{
private State state = new State();
@Test
public void testSetState()
{
{
final List<State.KeyValuePair> pairs = Arrays.asList( new State.KeyValuePair( "hunger", "Y" ) );
assertTrue( this.state.setState( pairs ) );
}
{
final List<State.KeyValuePair> pairs = Arrays.asList( new State.KeyValuePair( "hunger", "N" ) );
assertFalse( this.state.setState( pairs ) );
}
{
final List<State.KeyValuePair> pairs = Arrays.asList( new State.KeyValuePair( "hunger", "N" ),
new State.KeyValuePair( "sad", "N" ) );
assertTrue( this.state.setState( pairs ) );
}
}
}