NarendraR :
I'm automating an eCommerce website where i have to test whether sizes present in dropdown of a particular product are displayed in ascending order.
I declared contents list which holds the ascending order of size
public static final List<String> T_SHIRT_SIZE_LIST = Collections.unmodifiableList(Arrays.asList("Small (S)", "Medium (M)", "Large (L)", "X-Large (XL)", "XX-Large (XXL)"));
Now I've taken and store all the product size value in a list i.e.
List<String> list2 = Arrays.asList("Small (S)", "Medium (M)", "Large (L)","XX-Large (XXL)");
I want to compare the list2 contents should be in same order as T_SHIRT_SIZE_LIST
has, even though some value missing in list2.
Jason :
what you can instead do is use the Comparator/Comparable interface(s) to sort your list. You don't have to compare the two lists, just compare the elements in the list.
Edited to ensure you can convert from String to TShirtSize using a factory method.
enum TShirtSize {
SMALL(0, "Small (S)"),
MEDIUM(1, "Medium (M)"),
LARGE(2, "Large (L)"),
XL(3, "X-Large (XL)"),
XXL(4, "XX-Large (XXL)");
private final int order;
private final String identifier;
TShirtSize(int order, String identifier) {
this.order = order;
this.identifier = identifier;
}
public static TShirtSize valueOfId(String id) {
// cache use of values() in an immutable map/set
return Stream.of(values()).filter(size -> size.identifier.equals(id)).findAny().orElseThrow(IllegalArgumentException::new);
}
public String getIdentifier() {
return identifier;
}
public int getOrder() {
return order;
}
}
public static boolean isOrdered(List<TShirtSize> sizes) {
List<TShirtSize> sizesOrdered = sizes.stream().sorted(Comparator.comparingInt(TShirtSize::getOrder)).collect(Collectors.toList());
return IntStream.range(0, sizes.size()).allMatch(index -> sizes.get(index) == sizesOrdered.get(index));
}
List<String> actualSize = Arrays.asList("Small (S)", "Large (L)", "X-Large (XL)");
List<TShirtSize> actualSizeList = actualSize.stream().map(TShirtSize::valueOfId).collect(Collectors.toList());
System.out.println("is expected : " + isOrdered(actualSizeList));
Guess you like
Origin http://10.200.1.11:23101/article/api/json?id=416663&siteId=1