1

I am just practising java.

I have this ArrayList which contains duplicate values.

I want to loop through this list so that it can print these duplicate values by group.

here is what my method contains.

ArrayList nomero = new ArrayList();

    nomero.add(1);
    nomero.add(1);
    nomero.add(2);
    nomero.add(2);
    nomero.add(3);
    nomero.add(3);


    for(int i=0; i<nomero.size(); i++){

        System.out.println(nomero.get(i));

    }

and the it prints like below.

printed loop

what I wanna do is print it like

what iam trying

Please help me with this issue. Thanks.

1
  • 1
    if value != lastValue print new line so basically you need to know the last "group" value and when it changes, you print a new line Commented Jan 28, 2017 at 1:48

3 Answers 3

3

Simple enough, add a line break when the previous value is different from the current. But, you shouldn't use raw types. And you should sort the List (and prefer the interface to the concrete type). And you might use Arrays.asList to initialize your List. Something like,

List<Integer> nomero = new ArrayList<>(Arrays.asList(1, 1, 2, 2, 3, 3));
Collections.sort(nomero);
for (int i = 0; i < nomero.size(); i++) {
    if (i > 0 && nomero.get(i - 1) != nomero.get(i)) {
        System.out.println();
    }
    System.out.println(nomero.get(i));
}
Sign up to request clarification or add additional context in comments.

1 Comment

Great answers, I was going mad to figure out this. Simple and explanatory answers. Thanks a lot everyone.
1

So, at a very basic level, you need to know what the "last value" was, when it longer equals the "current value", you add a new line and update the "last value" to be equal to the "current value"

ArrayList<Integer> nomero = new ArrayList<>();

nomero.add(1);
nomero.add(1);
nomero.add(2);
nomero.add(2);
nomero.add(3);
nomero.add(3);

int lastValue = nomero.get(0);

for (int i = 0; i < nomero.size(); i++) {
    int nextValue = nomero.get(i);
    if (nextValue != lastValue) {
        System.out.println("");
        lastValue = nextValue;
    }
    System.out.println(nextValue);

}

This does assume that the list is already sorted

Comments

0

Java 8 made it simpler ...

List<Integer> nomero = Arrays.asList(1, 1, 2, 2, 3, 3);
Map<Integer, Long> map = nomero.stream().collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
    for (Integer i : map.keySet()) {
        for (int j = 0; j < map.get(i); j++) {
            System.out.println(i);
        }
        System.out.println();
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.