[英]Run two loops over Set
我有包含客戶對象的TreeSet
。 它包含10個圓形對象。 我想在集合上運行兩個循環,以便可以將每個元素與下面的所有元素進行比較。 這是我可以使用List
進行操作的示例,但是我不知道如何使用Set
for (int i = 0; i < set.size(); i++) {
// Circle circle = set.get(i);
for (int j = i+1; i < set.size(); j++) {
// Circle circle = set.get(j);
}
}
我可以使用List<String> list=new ArrayList<>(set)
做到這一點,在這里我既可以實現sorting(通過set),又可以在list上運行兩個循環,但這將是額外的內存。
我想實現的目標:-
對於外循環中的每個圓(按半徑按降序排列),如果該圓有效,我想計算內循環中的每個圓的面積(請假定圓對象中有一個屬性,該屬性可以判斷其是否有效) 。 如果有效,則需要計算外循環和內循環中的圓面積的乘積並找到最大結果
使用foreach:
for (Customer customer : set ) {
for (Customer otherCustomer : set ) {
// do your processing
}
}
您不能使用特定於List
接口的get(int index)
方法從Set
檢索元素。
抱歉,我沒有注意您的內循環情況:
for (int j = i+1; i < set.size(); j++) {
您確實希望內部循環在外部循環的當前元素之后開始。 您可以通過使用TreeSet
類聲明集合並使用tailSet()
方法來實現:
/**
* @throws ClassCastException {@inheritDoc}
* @throws NullPointerException if {@code fromElement} is null and
* this set uses natural ordering, or its comparator does
* not permit null elements
* @throws IllegalArgumentException {@inheritDoc}
* @since 1.6
*/
public NavigableSet<E> tailSet(E fromElement, boolean inclusive) {
return new TreeSet<>(m.tailMap(fromElement, inclusive));
}
因此,您可以在外部循環的當前元素之后開始第二個循環:
TreeSet<Customer> set = new TreeSet();
for (Customer customer : set) {
for (Customer otherCustomer : set.tailSet(customer, false) {
// do your processing
System.out.println("");
}
}
您可以使用tailSet
來獲取從當前項開始的所有項:
for (Customer outer : treeSet ) {
for (Customer inner : treeSet.tailSet(outer, false)) {
// ...
}
}
注意您需要向其傳遞false
的第二個參數。 它告訴集合排除outer
元素。
您可以為它實現Comparator接口。 默認情況下,它將根據您的要求進行排序。
請在下面找到相同的代碼。
import java.util.Comparator;
import java.util.TreeSet;
public class Main {
public static void main(String a[]){
//I am sorting list by name.
TreeSet<Empl> empls = new TreeSet<Empl>(new EmplNameComp());
empls.add(new Empl("Jitendra",3000));
empls.add(new Empl("Kumar",6000));
empls.add(new Empl("Balla",2000));
empls.add(new Empl("Puja",2400));
for(Empl e:empls){
System.out.println(e);
}
System.out.println("=====END======");
}
}
class EmplNameComp implements Comparator<Empl>{
@Override
public int compare(Empl e1, Empl e2) {
return e1.getName().compareTo(e2.getName());
}
}
class Empl{
private String name;
private int salary;
public Empl(String n, int s){
this.name = n;
this.salary = s;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
public String toString(){
return "Name: "+this.name+" AND Salary: "+this.salary;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.