Using Iterator, if there is the same element in the list, please tell me how to remove it.

Asked 1 years ago, Updated 1 years ago, 380 views

I have a question for the program below.

入力If the same number is included in the listnumber entered and the number is included, I would like to delete the next number.
I wrote like the code below, but it doesn't work.How should I write it?

 if(i==i) {it.removes();}

「I wanted to write a program called "If 0 is included, I will delete it," so when I wrote the code below, I got an error, so I used Iterator.Why should I use Iterator instead of the following for statement?

 for (listnumber==0) {remove.listnumber[i]}

Below is the full code.

import java.util.*;

import java.util.List;

public class Main2 {
  

  public static void main(String[]args) {
    

    Scanner sc = new Scanner (System.in);
    
    
    ArrayList<Integer>listnumber = new ArrayList<Integer>(); 
    for(inti=0;i<10;i++){
    
    
    int number = sc.nextInt();
    listnumber.add(number);
    
    }
    System.out.println("nyuryoku End";

      // It's beautiful to write like this using an iterator.
      
      
      while(it.hasNext()){
        inti = it.next();
        // If the element in the list contains zero, delete it
        if(i==0) {it.remove();}
        // If the list contains the same number, delete it
        if(i==i){it.removes();}
    }
     System.out.println("Number of registered data:" + listnumber.size());

    for(intn=0;n<listnumber.size();n++){

     System.out.println("listnumber" + listnumber.get(n));
    }
    }
  
}

java

2022-09-30 21:53

1 Answers

It doesn't work.How should I write it?

This is because you are comparing your values with the condition that they always return true.It's rather troublesome to write this myself.
I don't want to include the same value there.
I don't want to include certain characters.
Easy to handle data shaping such as Stream API makes it easy to express, but can't you do that?

Scanner sc=new Scanner (System.in);
        List<Integer>listnumber=sc.tokens().filter(
            o->o!=null&!o.equals("0") // Remove Null and 0
            .map(s->Integer.parseInt(s))// String->Integer Translation
            .distinct() // Delete Duplicate Data
            .collect(Collectors.toList());// Stream->List Translation


2022-09-30 21:53

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.