Java Code Examples for java.util.LinkedList#peekLast()

The following examples show how to use java.util.LinkedList#peekLast() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: StackUtils.java    From super-csv-annotation with Apache License 2.0 6 votes vote down vote up
/**
 *  スタックの最後の要素(一番下の要素)が引数で指定した文字列の何れかと等しいかどうか比較する。
 * @param stack
 * @param strs
 * @return
 */
public static boolean equalsAnyBottomElement(final LinkedList<String> stack, final String[] strs) {
    Objects.requireNonNull("stack should not be null.");
    Objects.requireNonNull("strs should not be null.");
    
    if(stack.isEmpty()) {
        return false;
    }
    
    final String bottom = stack.peekLast();
    for(String str : strs) {
        if(str.equals(bottom)) {
            return true;
        }
    }
    
    return false;
    
}
 
Example 2
Source File: StackUtils.java    From xlsmapper with Apache License 2.0 6 votes vote down vote up
/**
 *  スタックの最後の要素(一番下の要素)が引数で指定した文字列の何れかと等しいかどうか比較する。
 * @param stack
 * @param strs
 * @return
 */
public static boolean equalsAnyBottomElement(final LinkedList<String> stack, final String[] strs) {
    
    ArgUtils.notNull(stack, "stack");
    ArgUtils.notEmpty(strs, "strs");
    
    if(stack.isEmpty()) {
        return false;
    }
    
    final String bottom = stack.peekLast();
    for(String str : strs) {
        if(str.equals(bottom)) {
            return true;
        }
    }
    
    return false;
    
}
 
Example 3
Source File: MagicQueue.java    From snowblossom with Apache License 2.0 6 votes vote down vote up
/**
 * @param data A byte buffer open for writes
 */
private void writeToBucket(int bucket, ByteBuffer data)
{
  LinkedList<ByteBuffer> lst = global_buckets[bucket];
  synchronized(lst)
  {
    ByteBuffer last = lst.peekLast();
    if ((last != null) && (last.remaining() >= data.position()))
    {
      data.flip();
      last.put(data);
    }
    else
    {
      lst.add(data);
    }
  }
}
 
Example 4
Source File: ApexCli.java    From attic-apex-core with Apache License 2.0 6 votes vote down vote up
private List<String> startNewCommand(LinkedList<List<String>> resultBuffer)
{
  List<String> newCommand = new ArrayList<>();
  if (!resultBuffer.isEmpty()) {
    List<String> lastCommand = resultBuffer.peekLast();
    if (lastCommand.size() == 1) {
      String first = lastCommand.get(0);
      if (first.matches("^[A-Za-z][A-Za-z0-9]*=.*")) {
        // This is a variable assignment
        int equalSign = first.indexOf('=');
        variableMap.put(first.substring(0, equalSign), first.substring(equalSign + 1));
        resultBuffer.removeLast();
      }
    }
  }
  resultBuffer.add(newCommand);
  return newCommand;
}
 
Example 5
Source File: StatsItemAggregationEntry.java    From java-trader with Apache License 2.0 6 votes vote down vote up
/**
 * 计算方式: 区间内开始结束两个数据, 计算差值的分钟平均.
 */
private double getCumulativeAvgValuePerMinute(LinkedList<SampleValueEntry> values, int maxMinutes)
{
    SampleValueEntry lastEntry = values.peekLast();
    SampleValueEntry firstEntry = lastEntry;

    for( Iterator<SampleValueEntry> it=values.descendingIterator(); it.hasNext(); ) { //从后向前逆序
        SampleValueEntry entry = it.next();
        if ( (lastEntry.getTime()-entry.getTime())>maxMinutes*60 ) {
            break;
        }
        firstEntry = entry;
    }
    BigDecimal v = new BigDecimal((lastEntry.getValue()-firstEntry.getValue()), VALUE_CONTEXT);
    long minutes = ((lastEntry.getTime()-firstEntry.getTime())+30) / 60;
    if ( minutes<=0 ) {
        minutes = 1;
    }
    BigDecimal av = v.divide(new BigDecimal(minutes), RoundingMode.HALF_UP);
    return av.doubleValue();
}
 
Example 6
Source File: ApexCli.java    From Bats with Apache License 2.0 6 votes vote down vote up
private List<String> startNewCommand(LinkedList<List<String>> resultBuffer)
{
  List<String> newCommand = new ArrayList<>();
  if (!resultBuffer.isEmpty()) {
    List<String> lastCommand = resultBuffer.peekLast();
    if (lastCommand.size() == 1) {
      String first = lastCommand.get(0);
      if (first.matches("^[A-Za-z][A-Za-z0-9]*=.*")) {
        // This is a variable assignment
        int equalSign = first.indexOf('=');
        variableMap.put(first.substring(0, equalSign), first.substring(equalSign + 1));
        resultBuffer.removeLast();
      }
    }
  }
  resultBuffer.add(newCommand);
  return newCommand;
}
 
Example 7
Source File: CommandInjection.java    From Android_Code_Arbiter with GNU Lesser General Public License v3.0 5 votes vote down vote up
private String transferThroughList(String in, int index) {
    LinkedList<String> list = new LinkedList<String>();
    list.add(System.getenv("")); // taints the list
    list.clear(); // makes the list safe again
    list.add(1, "xx");
    list.addFirst(in); // can taint the list
    list.addLast("yy");
    list.push(in);
    return list.element() + list.get(index) + list.getFirst() + list.getLast()
            + list.peek() + list.peekFirst() + list.peekLast() + list.poll()
            + list.pollFirst() + list.pollLast() + list.pop() + list.remove()
            + list.remove(index) + list.removeFirst() + list.removeLast()
            + list.set(index, "safe") + list.toString();
}
 
Example 8
Source File: UidRange.java    From james-project with Apache License 2.0 5 votes vote down vote up
private static LinkedList<Range<MessageUid>> mergeContiguousRanges(RangeSet<MessageUid> rangeSet) {
    LinkedList<Range<MessageUid>> mergedRanges = new LinkedList<>();
    
    for (Range<MessageUid> range: rangeSet.asRanges()) {
        Range<MessageUid> previous = mergedRanges.peekLast();
        if (rangesShouldBeMerged(range, previous)) {
            replaceLastRange(mergedRanges, mergeRanges(range, previous));
        } else {
            mergedRanges.add(range);
        }
    }
    return mergedRanges;
}
 
Example 9
Source File: Fusion.java    From SPADE with GNU General Public License v3.0 5 votes vote down vote up
private void checkLists(LinkedList sourceList, LinkedList destinationList, boolean compare) {
    // Comparison and fusion is done if the compare flag is set
    if (compare) {
        // Get the most recently added element to the source list. This is
        // compared to all the elements in the other list
        Object newElement = sourceList.peekLast();
        if (newElement instanceof AbstractVertex) {
            AbstractVertex newVertex = (AbstractVertex) newElement;
            for (int i = 0; i < destinationList.size(); i++) {
                Object otherElement = destinationList.get(i);
                if (otherElement instanceof AbstractVertex) {
                    AbstractVertex otherVertex = (AbstractVertex) otherElement;
                    // This condition is used to check for elements in the list that
                    // have already been fused in which case comparison and fusion
                    // is unnecessary
                    if (!otherVertex.getAnnotation(SOURCE_REPORTER).equalsIgnoreCase(FUSED_SOURCE_REPORTER)
                            && compare(newVertex, otherVertex)) {
                        fuseAndReplace(newVertex, otherVertex);
                    }
                }
            }
        }
    }
    // Check if the list size is exceeded. If yes, remove the element from
    // the head of the list and forward it to the next filter
    if (sourceList.size() > MAX_LIST_LENGTH) {
        Object removedElement = sourceList.poll();
        if (removedElement instanceof AbstractVertex) {
            putInNextFilter((AbstractVertex) removedElement);
        } else if (removedElement instanceof AbstractEdge) {
            putInNextFilter((AbstractEdge) removedElement);
        }
    }
}
 
Example 10
Source File: DefaultMemoryEventStore.java    From super-cloudops with Apache License 2.0 5 votes vote down vote up
@Override
public synchronized Partition largest() {
	if (!this.records.isEmpty()) {
		// Expired clean.
		this.checkExpiredSampleClean();

		LinkedList<Partition> records0 = this.getASCRecords();
		Partition part = records0.peekLast();
		if (part != null) {
			part.setSamples(records0.size());
			return part;
		}
	}
	return null;
}
 
Example 11
Source File: Offer59I.java    From Project with Apache License 2.0 5 votes vote down vote up
public int[] maxSlidingWindow(int[] nums, int k) {
    if (nums == null || k < 1 || nums.length < k) {
        return new int[0];
    }

    LinkedList<Integer> maxList = new LinkedList<Integer>();
    int[] res = new int[nums.length - k + 1];
    int index = 0;
    for (int i = 0; i < nums.length; i++) {
        // 更新双端队列,如果双端队列不为空,并且尾结点(存的是下标)对应数组中的值是否小于等于当前值
        while (!maxList.isEmpty() && nums[maxList.peekLast()] <= nums[i]) {
            maxList.pollLast();
        }
        // 上面一直弹出,直到不符合然后加上当前值。
        maxList.addLast(i);
        // 上面加法是通用的,但是减法是针对该题定制的
        // 当过期的时候(当窗口形成之后再扩充才算过期)即窗口长度 > k,窗口形成过程中不会过期, i - k 表示过期的下标
        if (maxList.peekFirst() == i - k) {
            maxList.pollFirst();
        }
        // 判断下标过期
        if (i >= k - 1) {
            // 当窗口已经形成了,记录每一步的res
            res[index++] = nums[maxList.peekFirst()];
        }
    }
    return res;
}
 
Example 12
Source File: AllLessNumSubArray.java    From Project with Apache License 2.0 5 votes vote down vote up
/**
 * 使用双向最大最小值更新结构,时间复杂度为 O(N)
 */
public static int getNum(int[] arr, int num) {
    if (arr == null || arr.length == 0) {
        return 0;
    }
    // 分别准备最大值和最小值更新结构
    LinkedList<Integer> qmax = new LinkedList<Integer>();
    LinkedList<Integer> qmin = new LinkedList<Integer>();
    int L = 0;
    int R = 0;
    int res = 0;
    while (L < arr.length) {
        while (R < arr.length) {
            while (!qmin.isEmpty() && arr[qmin.peekLast()] >= arr[R]) {
                qmin.pollLast();
            }
            qmin.addLast(R);
            while (!qmax.isEmpty() && arr[qmax.peekLast()] <= arr[R]) {
                qmax.pollLast();
            }
            qmax.addLast(R);
            // 不达标
            if (arr[qmax.getFirst()] - arr[qmin.getFirst()] > num) {
                break;
            }
            R++;
        }
        if (qmin.peekFirst() == L) {
            qmin.pollFirst();
        }
        if (qmax.peekFirst() == L) {
            qmax.pollFirst();
        }
        res += R - L;
        // 换一个开头
        L++;
    }
    return res;
}
 
Example 13
Source File: SlidingWindowMaxArray.java    From Project with Apache License 2.0 5 votes vote down vote up
public static int[] getMaxWindow(int[] arr, int w) {
    if (arr == null || w < 1 || arr.length < w) {
        return null;
    }
    // LinkedList 就是一个标准的双向链表
    LinkedList<Integer> maxList = new LinkedList<Integer>();
    // 生成的结果数组
    int[] res = new int[arr.length - w + 1];
    int index = 0;
    for (int i = 0; i < arr.length; i++) {
        // 更新双端队列,如果双端队列不为空,并且尾结点(存的是下标)对应数组中的值是否小于等于当前值
        while (!maxList.isEmpty() && arr[maxList.peekLast()] <= arr[i]) {
            maxList.pollLast();
        }
        // 上面一直弹出,直到不符合然后加上当前值。
        maxList.addLast(i);
        // 上面加法是通用的,但是减法是针对该题定制的
        // 当过期的时候(当窗口形成之后再扩充才算过期)即窗口长度 > w,窗口形成过程中不会过期, i - w表示过期的下标
        if (maxList.peekFirst() == i - w) {
            maxList.pollFirst();
        }
        // 判断下标过期
        if (i >= w - 1) {
            // 当窗口已经形成了,记录每一步的res
            res[index++] = arr[maxList.peekFirst()];
        }
    }
    return res;
}
 
Example 14
Source File: SOLRTrackingComponentImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Does a 'breadth first' search of ancestors, caching as it goes
 * @param nodeIds initial list of nodes to visit
 * @return all visited nodes, in no particular order
 */
private List<Long> cacheAncestors(List<Long> nodeIds)
{
    final LinkedList<Long> toVisit = new LinkedList<Long>(nodeIds);
    Set<Long> visited = new TreeSet<Long>();
    Long nodeId;
    nodeDAO.cacheNodesById(toVisit);
    Long lastCached = toVisit.peekLast();
    while ((nodeId = toVisit.pollFirst()) != null)
    {
        if (visited.add(nodeId) && (nodeDAO.getNodeIdStatus(nodeId) != null) && (false == nodeDAO.getNodeIdStatus(nodeId).isDeleted()))
        {
            nodeDAO.getParentAssocs(nodeId, null, null, null, new ChildAssocRefQueryCallback()
            {
                @Override
                public boolean preLoadNodes()
                {
                    return false;
                }

                @Override
                public boolean orderResults()
                {
                    return false;
                }

                @Override
                public boolean handle(Pair<Long, ChildAssociationRef> childAssocPair,
                        Pair<Long, NodeRef> parentNodePair, Pair<Long, NodeRef> childNodePair)
                {
                    toVisit.add(parentNodePair.getFirst());
                    return true;
                }

                @Override
                public void done()
                {
                }
            });
        }
        final boolean nodeIdEqualsLastCached = (nodeId == null && lastCached == null) ||
                                               (nodeId != null && nodeId.equals(lastCached));
        if (nodeIdEqualsLastCached && !toVisit.isEmpty())
        {
            nodeDAO.cacheNodesById(toVisit);
            lastCached = toVisit.peekLast();
        }
    }
    return new ArrayList<Long>(visited);
}
 
Example 15
Source File: TraceTableModel.java    From pega-tracerviewer with Apache License 2.0 4 votes vote down vote up
private TraceEvent getMatchingParentTraceEvent(TraceEvent childTraceEvent) {

        TraceEvent parentTraceEvent = null;

        LinkedList<TraceEvent> treeBuildTraceEventList = getTreeBuildTraceEventList();

        Iterator<TraceEvent> descendingIterator = treeBuildTraceEventList.descendingIterator();

        while (descendingIterator.hasNext()) {

            TraceEvent traceEvent = descendingIterator.next();

            if (traceEvent.isMatchingParentTraceEvent(childTraceEvent)) {
                parentTraceEvent = traceEvent;
                break;
            }
        }

        // if no possible parent found, assign it to last start block
        if ((parentTraceEvent == null)) {
            parentTraceEvent = treeBuildTraceEventList.peekLast();
        }

        return parentTraceEvent;
    }
 
Example 16
Source File: NestRouteStrategy.java    From jstarcraft-core with Apache License 2.0 4 votes vote down vote up
@Override
public String chooseDataSource(List<String> keys) {
    LinkedList<String> context = contexts.get();
    return context.peekLast();
}
 
Example 17
Source File: TransferArchiveReader.java    From packagedrone with Eclipse Public License 1.0 4 votes vote down vote up
public void process ( final Handler handler ) throws IOException
{
    Objects.requireNonNull ( handler );

    final Map<List<String>, String> paths = new HashMap<> ();
    Map<MetaKey, String> properties = null;
    String fullName = null;

    ZipEntry entry;
    while ( ( entry = this.stream.getNextEntry () ) != null )
    {
        final String name = entry.getName ();
        final LinkedList<String> path = makePath ( name );

        if ( path.isEmpty () )
        {
            throw new IllegalStateException ( "Invalid path entry: " + name );
        }

        if ( name.endsWith ( "/content" ) )
        {
            if ( paths.containsKey ( path ) )
            {
                throw new IllegalStateException ( String.format ( "Artifact %s already processed", path.stream ().collect ( Collectors.joining ( " -> " ) ) ) );
            }
            if ( properties == null )
            {
                throw new IllegalStateException ( "The 'properties.json' file must be stored before the 'content' stream" );
            }

            // make parent path and fetch ID

            final LinkedList<String> parentPath = new LinkedList<> ( path );
            parentPath.removeLast ();
            final String parentId = paths.get ( parentPath );

            // make full name

            if ( fullName == null )
            {
                fullName = path.peekLast ();
            }

            // handle

            final String id = handler.handleEntry ( parentId, fullName, properties, new CloseShieldInputStream ( this.stream ) );

            // store ID

            paths.put ( path, id );

            // reset properties

            properties = null;
            fullName = null;

            // store
        }
        else if ( name.endsWith ( "/properties.json" ) )
        {
            // load properties
            properties = loadProperties ( new CloseShieldInputStream ( this.stream ) );
        }
        else if ( name.endsWith ( "/name" ) )
        {
            fullName = Streams.toString ( this.stream, StandardCharsets.UTF_8 );
        }
        else
        {
            throw new IllegalStateException ( "Invalid path entry: " + name );
        }
    }
}
 
Example 18
Source File: TtmlParser.java    From Exoplayer_VLC with Apache License 2.0 4 votes vote down vote up
@Override
public Subtitle parse(InputStream inputStream, String inputEncoding, long startTimeUs)
    throws IOException {
  try {
    XmlPullParser xmlParser = xmlParserFactory.newPullParser();
    xmlParser.setInput(inputStream, inputEncoding);
    TtmlSubtitle ttmlSubtitle = null;
    LinkedList<TtmlNode> nodeStack = new LinkedList<TtmlNode>();
    int unsupportedNodeDepth = 0;
    int eventType = xmlParser.getEventType();
    while (eventType != XmlPullParser.END_DOCUMENT) {
      TtmlNode parent = nodeStack.peekLast();
      if (unsupportedNodeDepth == 0) {
        String name = xmlParser.getName();
        if (eventType == XmlPullParser.START_TAG) {
          if (!isSupportedTag(name)) {
            Log.i(TAG, "Ignoring unsupported tag: " + xmlParser.getName());
            unsupportedNodeDepth++;
          } else {
            try {
              TtmlNode node = parseNode(xmlParser, parent);
              nodeStack.addLast(node);
              if (parent != null) {
                parent.addChild(node);
              }
            } catch (ParserException e) {
              if (strictParsing) {
                throw e;
              } else {
                Log.e(TAG, "Suppressing parser error", e);
                // Treat the node (and by extension, all of its children) as unsupported.
                unsupportedNodeDepth++;
              }
            }
          }
        } else if (eventType == XmlPullParser.TEXT) {
          parent.addChild(TtmlNode.buildTextNode(xmlParser.getText()));
        } else if (eventType == XmlPullParser.END_TAG) {
          if (xmlParser.getName().equals(TtmlNode.TAG_TT)) {
            ttmlSubtitle = new TtmlSubtitle(nodeStack.getLast(), startTimeUs);
          }
          nodeStack.removeLast();
        }
      } else {
        if (eventType == XmlPullParser.START_TAG) {
          unsupportedNodeDepth++;
        } else if (eventType == XmlPullParser.END_TAG) {
          unsupportedNodeDepth--;
        }
      }
      xmlParser.next();
      eventType = xmlParser.getEventType();
    }
    return ttmlSubtitle;
  } catch (XmlPullParserException xppe) {
    throw new ParserException("Unable to parse source", xppe);
  }
}