# 条件循环在Java中

go评论79阅读模式

Condition for loops in java

# 问题

``````while (part[i].compareToIgnoreCase(part[i-1]) < 0) {
smaller = myarr[i];
myarr[i] = myarr[i-1];
myarr[i-1] = smaller;
i--;
if (i <= 0) {
break;
}
}
``````

``````while (Integer.parseInt(part[i]) < Integer.parseInt(part[i-1])) {
smaller = myarr[i];
myarr[i] = myarr[i-1];
myarr[i-1] = smaller;
i--;
if (i <= 0) {
break;
}
}
``````

I have 2 loops.

The first:

``````while(part[i].compareToIgnoreCase(part[i-1])&lt;0) {
smaller = myarr[i];
myarr[i] = myarr[i-1];
myarr[i-1] = smaller;
i--;
if(i&lt;=0) {
break;
}
``````

The second:

``````while(Integer.parseInt(part[i]) &lt; Integer.parseInt(part[i-1])) {
smaller = myarr[i];
myarr[i] = myarr[i-1];
myarr[i-1] = smaller;
i--;
if(i&lt;=0) {
break;
}
``````

If you notice, both the loops perform the same task. Just the conditions are different. The conditions can not be passed in together i.e.only one can be used at a time.(Because these loops are a part of a method and 2 String arrays with different content are passed in.)

Can I somehow merge both of these together and do something so that only one condition is picked up at a time?

# 答案1

``````  public void bubbleSort(String[] part, BiPredicate<String, String> predicate) {
while(predicate.test(part[i], part[i-1])) {
// 进行冒泡排序操作
}
}

public void bubbleSort(String[] part) {
if (isText) {
bubbleSort(part, (l, r) -> l.compareToIgnoreCase(r) < 0);
} else {
bubbleSort(part, (l, r) -> Integer.parseInt(l) < Integer.parseInt(r));
}
}
``````

``````Arrays.sort(part, String::compareToIgnoreCase); // 按文本排序
Arrays.sort(part, Comparator.comparingInt(Integer::parseInt)); // 按数字排序
``````

Sounds like you are asking how to take a `Predicate` (`BiPredicate&lt;String, String&gt;` to be precise) as a parameter.

``````  public void bubbleSort(String[] part, BiPredicate&lt;String, String&gt; predicate) {
while(predicate.test(part[i], part[i-1])) {
// Do bubblesort stuff
}
}

public void bubbleSort(String[] part) {
if (isText) {
bubbleSort(part, (l, r) -&gt; l.compareToIgnoreCase(r) &lt; 0);
} else {
bubbleSort(part, (l, r) -&gt; Integer.parseInt(l) &lt; Integer.parseInt(r));
}
}
``````

That said there are better ways to sort arrays!

``````Arrays.sort(part, String::compareToIgnoreCase); // Sort by text
Arrays.sort(part, Comparator.comparingInt(Integer::parseInt)); // Sort by number
``````

• 本文由 发表于 2020年7月28日 07:24:18
• 转载请务必保留本文链接：https://go.coder-hub.com/63124997.html
• java

go 55

go 51

go 60

go 59