Solved

How to insert a line in between Collections in Java?

Posted on 2009-04-07
6
206 Views
Last Modified: 2012-06-21
Hi,

I got stuck at using Collections to control my arraylist to be displayed in a combo box. I stored all details in a csv file and i am loading everything according to sequence specified in one of the csv column value. Say this is my sample data

a001|mango|1|A
a002|apple|1|A
a003|spinach|2|B
a004|grapes|1|A
a005|carrot|2|B

i need combo box to display
mango
apple
grapes
----------
spinach
carrot

is there a way to include the horizontal dotted line (i use var 'separator' to denote dotted lines) above? The current code use as below
Collections.sort(allList, new Comparator()

{

  public int compare (Object o1, Object o2)

  {	

      boolean ascending = true;

      String row1 = (String)((ArrayList)o1).get(2);

      String row2 = (String)((ArrayList)o2).get(2);

      if (ascending==true)

      {

          int getcompare = row1.compareTo(row2);

          if (getcompare != 0)

          {

              row1.concat(separator);

          }

          return getcompare;	

          //return row1.compareTo(row2);

     }

     else

         return row2.compareTo(row1);

 }

});

						

targetList.add(detailList.get(j).get(1));

Iterator stepper = targetList.iterator();

while (stepper.hasNext())

{

     String current = (String)stepper.next();

     System.out.println(current);

}

Open in new window

0
Comment
Question by:ai_chien
  • 3
  • 2
6 Comments
 
LVL 12

Expert Comment

by:Gibu George
ID: 24087812
Whats in the detailList, allList etc? Can you put the whole code instead of the snippet?
0
 
LVL 19

Expert Comment

by:Jim Cakalic
ID: 24087994
Being a fan of the Apache Commons Collections, I would use the CollectionUtils.select method to extract a subcollection that matches a Predicate. In this case you don't need to do any sorting. Assuming you stick with the pipe-separated Strings from the file, it would look something like the code snippet below.

The SequencePredicate class implements the required Predicate interface so that it can be used by the select method. CollectionUtils.select iterates over the input Collection calling the Predicate.evaluate method for each object. If the evaluate method returns true then the object is placed in the output Collection which is returned when the iteration ends.

Now that you have a Collection with all matching objects you can do something with it. This snippet just prints it. Your code will do something clever like add the name field to the ComboBox. Notice that it is easy at this point to add the separator. The code gets objects with a sequence field value that matches "1" and prints them. Then it prints the separator. Then it gets objects with a sequence field value that matches "2" and prints them.

Anyway, that's one way to approach it without sorting. The code gets a little clearer if you actually have a class that represents each line in the file ...
    private static class SequencePredicate implements Predicate {

        private String sequence;
 

        public SequencePredicate(String sequence) {

            this.sequence = sequence;

        }

        public boolean evaluate(Object arg) {

            return ((String) arg).split("\\|")[2].equals(this.sequence);

        }

    }

    

    private void process(List<String> allList) {

        // get and print all Strings with a sequence field of "1"

        print((Collection<String>) CollectionUtils.select(allList, new SequencePredicate("1")));

        // print the separator

        System.out.println(separator);

        // get and print all Strings with a sequence field of "2"

        print((Collection<String>) CollectionUtils.select(allList, new SequencePredicate("2")));

    }
 

    private void print(Collection<String> strings) {

        for (String line : strings) {

            System.out.println(line.split("\\|")[1]);

        }

    }

Open in new window

0
 
LVL 19

Expert Comment

by:Jim Cakalic
ID: 24088074
Assuming a Fruit class like this the code would look like the snippet below.

class Fruit {
    public String id;
    public String name;
    public String sequence;
    public String alpha;

    public Fruit(String input) {
        String[] parts = input.split("\\|");
        this.id = parts[0];
        this.name = parts[1];
        this.sequence = parts[2];
        this.alpha = parts[3];
    }
}


    private static class SequencePredicate implements Predicate {

        private String sequence;
 

        public SequencePredicate(String sequence) {

            this.sequence = sequence;

        }

        public boolean evaluate(Object arg) {

            return ((Fruit) arg).sequence.equals(this.sequence);

        }

    }

    

    private void process(List<Fruit> allList) {

        // get and print all Strings with a sequence field of "1"

        print((Collection<Fruit>) CollectionUtils.select(allList, new SequencePredicate("1")));

        // print the separator

        System.out.println(separator);

        // get and print all Strings with a sequence field of "2"

        print((Collection<Fruit>) CollectionUtils.select(allList, new SequencePredicate("2")));

    }
 

    private void print(Collection<Fruit> fruits) {

        for (Fruit fruit : fruits) {

            System.out.println(fruit.name);

        }

    }

Open in new window

0
Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

 
LVL 19

Accepted Solution

by:
Jim Cakalic earned 100 total points
ID: 24088219
Of course, if you really want to do this by sorting then you could do it like this (again assuming a Fruit class as in my previous comment). The code is clearer IMO if you iterate the Collection twice picking out just the objects you want to handle. I'd actually question whether you even need to bother sorting the Collection since the order of lines within any group appears to be dictated by the order of lines in the file.
    private static class SequenceComparator implements Comparator {

        public int compare(Object o1, Object o2) {

            return ((Fruit) o1).sequence.compareTo(((Fruit) o2).sequence);

        }

    }
 

    private void process(List<Fruit> allList) {

        Collections.sort(allList, new SequenceComparator());

        // get and print all Strings with a sequence field of "1"

        print(allList, "1");

        // print the separator

        System.out.println(separator);

        // get and print all Strings with a sequence field of "2"

        print(allList, "2");

    }
 

    private void print(Collection<Fruit> fruits, String sequence) {

        for (Fruit fruit : fruits) 

            if (fruit.sequence.equals(sequence))

                System.out.println(fruit.name);

    }

Open in new window

0
 

Author Comment

by:ai_chien
ID: 24093364
thanks jim, i learnt a lot from you. I'll try and update again...
0
 

Author Comment

by:ai_chien
ID: 24093423
Hi all, i'm sorry to have confused anyone on those arraylist I've created.  The whole code has lots of parameter parsing in between classes. It was really a big challenge for me as I declared some arraylist of arraylist (nested arraylist) earlier on for referencing 2 csv files (because they have relations to each other). Any then i need to load the values in some order to a combo box, that's where i was stuck. I'm trying to keep the nested arraylist settings instead of changing it into a List. Still trying....
0

Featured Post

How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
countX 22 70
wordcount challenge 11 78
firstChar challenge 13 86
PDFBox - convert image to PDF, PDF resolution 3 70
Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…

746 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now