이 작동합니다 :
Comparator<String> startsWithComparator = new Comparator<String>() {
public int compare(String currentItem, String key) {
if(currentItem.startsWith(key)) {
return 0;
}
return currentItem.compareTo(key);
}
};
int index = Collections.binarySearch(items, "contact.", startsWithComparator);
그러나 정렬 및 이진 검색은 단일 패스 반복보다 효율적이다.
은 부록 :
위의 대답은 여기, 당신을 도와하지만이 (스칼라, 구글 컬렉션에서 영감) 또 다른 방법이다 :
여기
List<String> items = Arrays.asList("one", "two", "three", "four", "five", "six");
int index = find(items, startsWithPredicate("th"));
System.out.println(index);
public static Predicate<String> startsWithPredicate(final String key) {
return new Predicate<String>(){
@Override
public boolean apply(String item) {
return item.startsWith(key);
}
};
}
public static <T> int find(Collection<T> items, Predicate<T> predicate) {
int index = 0;
for(T item: items) {
if(predicate.apply(item)) {
return index;
}
index++;
}
return -1;
}
interface Predicate<T> {
boolean apply(T item);
}
는 것은 찾기입니다() 메소드는 아니다 당신의 '일치하는'논리로 묶여; 단지 술어를 만족하는 요소를 찾습니다. 예를 들어 다른 술어 구현을 전달할 수 있습니다. 'endsWith'를 find() 메소드로 검사 할 수 있으며 특정 문자열로 끝나는 찾은 항목을 반환합니다. 또한 find() 메소드는 모든 유형의 콜렉션에서 작동합니다. 필요한 것은 콜렉션 요소 유형의 요소를 부울로 변환하는 술어입니다. 간단한 로직을 둘러싼이 여러 줄의 코드는 자바가 일류 함수를 지원하지 못함을 보여줍니다. (정규식)
이렇게 할 때마다 목록을 정렬해야하는 경우 "구식"효과가 떨어집니다. – getekha