简体   繁体   中英

how to single the list of list in java

I have a code here that getting the List of List in java. But my problem now is the result in my server was repeatable...

Example

[2012-01-04, 3 , 2012-02-04, 4, 2012-05-04, 3][2012-01-04, 3 , 2012-02-04, 4, 2012-05-04, 3][2012-01-04, 3 , 2012-02-04, 4, 2012-05-04, 3]

The value number of value inside my array is the same 3 group of arrays appearing.
This is my code. please help me.

SortedSet<String> uniqueSet = new TreeSet<String>(arrlist);
  ArrayList<ArrayList<String>> listOLists = new ArrayList<ArrayList<String>>();
  // List<String> flat = list.stream().flatMap(List::stream).collect(Collectors.toList());
  ArrayList<String> singleList = new ArrayList<String>();
  for(String date : uniqueSet) { 
    int counts = Collections.frequency(arrlist, date);
     Logger.debug("date: "+ date + " counts: " +counts);
      singleList.add(date);
      singleList.add(Integer.toString(counts));
      listOLists.add(singleList);

    }
    Logger.debug("Sample List: " + listOLists);
    return listOLists;
}

You're modifying and adding the same list. Probably you want to declare it inside the loop.

SortedSet<String> uniqueSet = new TreeSet<String>(arrlist);
  ArrayList<ArrayList<String>> listOLists = new ArrayList<ArrayList<String>>();
  // List<String> flat = list.stream().flatMap(List::stream).collect(Collectors.toList());
  for(String date : uniqueSet) { 
    int counts = Collections.frequency(arrlist, date);
     Logger.debug("date: "+ date + " counts: " +counts);
      ArrayList<String> singleList = new ArrayList<String>();
      singleList.add(date);
      singleList.add(Integer.toString(counts));
      listOLists.add(singleList);

    }
    Logger.debug("Sample List: " + listOLists);
    return listOLists;
}

Your mistake is that you create the inner list only once before the loop. You then change that single list instance in every loop run with inserting the same list instance again and again to the outer list.

Changing that single list instance will change all occurrences of it in the outer list.

So simply move the line

ArrayList<String> singleList = new ArrayList<String>();

inside the loop. This will then create a new inner list at each loop run.

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