Click here to Skip to main content
15,509,806 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
We consider a deck of playing cards in the following format:

Ranks: 2, 3, 4, 5, 6, 7, 8, 9, T, J, Q, K, A

Suits: S - Spade, D - Diamond, H - Heart, C - Club

Every card will be identified by 2 characters E.g. "3S" (3 of Spades), "TC" (10 of Club), "AH" (Ace of Heart).

I want to modify the getCardsBySuit function in order to return a Stream with all the cards belonging to that suit.

E.g. for a list that contains "2H", "3S", "TH" and the suit is 'H', the result should be a stream containing "2H" and "TH"

Java
public static Stream<String> getCardsBySuit(List<String> cards, char suit) 
{
    return null;
}


What I have tried:

public static Stream<String> getCardsBySuit(List<String> cards, char suit)
		{
			
			return cards.stream()
			    .filter(e -> e.startsWith(e, 'S'))
			    .filter(e -> e.startsWith(e, 'D'))
			    .filter(e -> e.startsWith(e, 'H'))
			    .filter(e -> e.startsWith(e, 'C'));
		}
Posted
Updated 31-May-21 6:07am
Comments
Richard MacCutchan 31-May-21 10:46am    
You only need one filter, and it should use the suit parameter from the call. You are also using startsWith in your filter, but the card names end with the suit.
BZR1990 31-May-21 10:59am    
Thank you ! :)

1 solution

Java
public static Stream<String> getCardsBySuit(List<String> cards, char suit)
{
	return cards.stream()
	    .filter(e -> e.endsWith(suit));
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900