简体   繁体   中英

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.

打印循环

what I wanna do is print it like

我在想什么

Please help me with this issue. Thanks.

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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