user1971804
user1971804

Reputation: 111

How to loop through ArrayList for different values in java

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.

Upvotes: 1

Views: 522

Answers (3)

user3325637
user3325637

Reputation: 124

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();
    }

Upvotes: 0

MadProgrammer
MadProgrammer

Reputation: 347194

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

Upvotes: 1

Elliott Frisch
Elliott Frisch

Reputation: 201439

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));
}

Upvotes: 3

Related Questions