Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
678 views
in Technique[技术] by (71.8m points)

arrays - Java, return if trimmed String in List contains String

In Java, I want to check whether a String exists in a List<String> myList.

Something like this:

if(myList.contains("A")){
    //true
}else{
    // false
}

The problem is myList can contain un-trimmed data:

{'  A', 'B  ', '  C  '}

I want it to return true if my item 'B' is in the list. How should I do this? I would like to avoid a looping structure.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

With Java 8 Stream API:

List<String> myList = Arrays.asList("  A", "B  ", "  C  ");
return myList.stream().anyMatch(str -> str.trim().equals("B"));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...