简体   繁体   English

从ArrayList按字母顺序返回元素

[英]Returning Elements From ArrayList Alphabetically

I'm working on a program to manipulate chemical formulae, and I'm writing a method which needs to loop through an ArrayList called "terms" and return the first one alphabetically. 我正在开发一个用于操纵化学式的程序,并且正在编写一种方法,该方法需要遍历称为“项”的ArrayList并按字母顺序返回第一个。

eg terms = {Term('H',4),Term('C',2),Term('H',4),Term('C',1)} would return Term('C',2) 例如,terms = {Term('H',4),Term('C',2),Term('H',4),Term('C',1)}将返回Term('C',2)

I've written this code so far but it's not working. 到目前为止,我已经编写了此代码,但无法正常工作。 I'm a real beginner to the Java language. 我是Java语言的真正初学者。

public Term nextElement()
{
    int i = 0;
    for (i = 0; i < terms.size()-1; i++)
    {
        int j = 1;
        while (i + j <= terms.size())
        if (terms.get(i).getElement() > terms.get(i+j).getElement())
        {
            terms.remove(i+j++);
            return terms.get(i);
        }
    }
    return null;
}

I'd appreciate any ideas or suggestions to solve this problem. 对于解决此问题的任何想法或建议,我将不胜感激。 Thanks! 谢谢!

You have two options here: 您在这里有两个选择:

  1. Let your Term class implement Comparable interface and override its compareTo() method. 让您的Term类实现Comparable接口并覆盖其compareTo()方法。 Then you can use Collections.sort(listOfTerms) to sort them and loop through. 然后,您可以使用Collections.sort(listOfTerms)对它们进行排序并遍历。
  2. Add class TermComparator which implements Comparator interface, use Collections.sort(listOfTerms, new TermComparator()) and loops through the sorted list. 添加实现Comparator接口的TermComparator类,使用Collections.sort(listOfTerms, new TermComparator())并遍历排序后的列表。

use Collections.sort(terms); 使用Collections.sort(terms); it will arrange the list alphabetically. 它将按字母顺序排列列表。

This is what you need to do: 这是您需要做的:

List<Term> terms = //your list
Collections.sort(terms, new Comparator<Term>() {
    @Override
    public int compare(Term t1, Term t2) {
        return t1.getElement().compareTo(t2.getElement());
    }
});

CODE: 码:

public class CodeSample {


public static void main(String[] args) {
    List<Term> terms=new ArrayList<Term>();
    terms.add(new Term('H',4));
    terms.add(new Term('C',2));
    terms.add(new Term('H',4));
    terms.add(new Term('C',1));
    System.out.println("Before Sorting");
    for(Term term:terms){
        System.out.print(term.toString().concat(" "));
    }
    Collections.sort(terms,new Comparator<Term>() {
        @Override
        public int compare(Term object1, Term object2) {                
            if (object1.getElement() != object2.getElement()) {
                return object1.getElement() - object2.getElement();
            } else {
                return object2.getCount() - object1.getCount();
            }           
        }
    });
    //Sorted terms
    System.out.println("After Sorting");
    for(Term term:terms){
        System.out.print(term.toString().concat(" "));
    }
}

public static class Term{
    private char element;
    private int count;
    public Term(char element, int count) {
        super();
        this.element = element;
        this.count = count;
    }
    public char getElement() {
        return element;
    }
    public int getCount() {
        return count;
    }
    @Override
    public String toString() {
        return "Term [element=" + element + ", count=" + count + "]";
    }       
}
 }

OUTPUT: 输出:

Before Sorting
Term [element=H, count=4] Term [element=C, count=2] Term [element=H, count=4] Term [element=C, count=1] 
After Sorting
Term [element=C, count=2] Term [element=C, count=1] Term [element=H, count=4] Term [element=H, count=4] 

1- you can implement Comparable and override compareTo() 1-您可以实现Comparable并覆盖compareTo()

int compareTo(Object obj){
Term term = (Term)obj;
if(term.getElement < this.getElement())
  return 1;
else if (term.getElement == this.getElement())
  return 0;
else
  return -1;
}

then use 然后使用

Collection.sort(terms);

2- 2-

 public Term nextElement()
    {
        char minElement = 'Z';
        int index = 0;
        for (int i = 0; i < terms.size(); i++)
        {
            if (terms.get(i).getElement() < minElement)
            {
                minElement = terms.get(i).getElement();
                index = i;
            }
        }
        Term temp = terms.get(index);
        terms.remove(index)
        return temp;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM