LinkedList倒序遍历
public List<Integer> getNewsFeed(int userId) { List<Integer> res = new ArrayList<>(); ListIterator<Map.Entry<Integer, Integer>> iter = new ArrayList<Map.Entry<Integer, Integer>>(tuiwen.entrySet()).listIterator(tuiwen.size()); HashSet<Integer> myFollowee = follow.get(userId); while(iter.hasPrevious()) { Map.Entry<Integer, Integer> entry = iter.previous(); if(entry.getValue() == userId || (myFollowee != null && myFollowee.contains(entry.getValue()))) { res.add(entry.getKey()); if (res.size() == 10) break; } } return res; }
public class Traverse { public static void main(String[] args) { //循环list List<Integer> dataList = new ArrayList<>(); dataList.add(1); dataList.add(2); dataList.add(4); dataList.add(3); System.out.println(dataList); //方式一: foreach for(Integer data: dataList) { System.out.print(data + " "); } System.out.println(); //方式二,for 下标 for(int i = 0; i < dataList.size(); i ++) { System.out.print(dataList.get(i) + " "); } System.out.println(); //方式三:迭代器 Iterator<Integer> listIter = dataList.iterator(); while(listIter.hasNext()) { Integer data = listIter.next(); System.out.print(data + " "); } System.out.println(); //循环set HashSet<Integer> dataSet = new HashSet<>(); dataSet.addAll(dataList); System.out.println(dataSet); //方式一:foreach for(Integer data: dataSet) { System.out.print(data + " "); } System.out.println(); //方式二:迭代器 Iterator<Integer> setIter = dataSet.iterator(); while(setIter.hasNext()) { System.out.print(setIter.next() + " "); } System.out.println(); //循环映射 HashMap<Integer, Integer> dataMap = new HashMap<>(); dataMap.put(1,1); dataMap.put(2,2); dataMap.put(3,4); //方法一:迭代器 Iterator<Map.Entry<Integer, Integer>> entryIter = dataMap.entrySet().iterator(); while(entryIter.hasNext()) { Map.Entry<Integer, Integer> entry = entryIter.next(); System.out.println(entry.getKey() + " " + entry.getValue()); } //方法一:倒序迭代器 ListIterator<Map.Entry<Integer, Integer>> reEntryIter = new ArrayList<Map.Entry<Integer, Integer>>(dataMap.entrySet()).listIterator(dataMap.size()); while(reEntryIter.hasPrevious()) { Map.Entry<Integer, Integer> entry = reEntryIter.previous(); System.out.println(entry.getKey() + " " + entry.getValue()); } //方法二:foreach for(Map.Entry<Integer, Integer> entry: dataMap.entrySet()) { System.out.println(entry.getKey() + " " + entry.getValue()); } } }